R Basic

기본 of 기본

R을 설치하면 가지고 놀 수 있는 datasets가 기본으로 설치된다. 한번 들여다보자

trees dataset

   1 # trees란 무엇인가!
   2 ?trees
   3 
   4 # trees 데이타를 화면에 띄워보자
   5 trees # 혹은 print(trees)
   6 
   7 # data size(dimension)을 확인해보자.
   8 dim(trees)
   9 
  10 # 31 x 3 개의 숫자를 한번에 보려니 눈에도 안 들어오고 의미없다. 일부만 화면에 띄워보자.
  11 head(trees) # 첫 6개의 data point만 화면에 출력
  12 head(trees,10) # 첫 10개의 data point만 화면에 출력
  13 tail(trees,4) # 마지막 4개의 data point만 화면에 출력
  14 
  15 # 데이타의 평균, 최상값, 최소값, 중간값, 상위 25% 값, 하위 25% 값을 보고 싶다면,
  16 summary(trees)
  17 
  18 # 나무 높이의 평균, 최상값, 최소값, 중간값, 상위 25% 값, 하위 25% 값을 따로 보고 싶다면,
  19 mean(trees$Height) # mean(trees) 은 어떤 결과가 나오나?
  20 max(trees$Height) # max(trees) 은 어떤 결과가 나오나?
  21 min(trees$Height) # min(trees) 은 어떤 결과가 나오나?
  22 quantile(trees$Height) # quantile(trees) 은 어떤 결과가 나오나?
  23 
  24 # 아몰랑 그림으로 보여줘
  25 boxplot(trees)
  26 
  27 # 통계 계산값 말고, 모든 data point를 다 xy 평면에 찍어줘
  28 plot(trees)
  29 
  30 # 특별히 Girth 대비 Volume만 따로 xy 평면에 보여주되, xy 둘다 log scale 로 보겠어
  31 plot(Volume ~ Girth, data = trees, log = "xy")
  32 plot(trees$Girth, trees$Volume, log = "xy") # trees 데이타의 컬럼 이름을 이렇게 지정할 수도 있음
  33 plot(trees[,1], trees[,3], log = "xy") # trees 데이타의 컬럼 번호를 지정할 수도 있음
  34 
  35 ## Tip:
  36 ## data[row 번호, col 번호] 와 같이 data point의 index로 지정가능
  37 ## 여러개의 숫자(혹은 문자)를 묶을 때는 c( , , ) 혹은 c( : ) 형식을 사용함
  38 trees[c(3:10), c(1,3)]
  39 plot(trees[c(3:10), c(1,3)])
  40 
  41 ## 궁극의 Tip:
  42 ## Console에서 위화살표 키를 누르면 전에 쳤던 명령문이 복사된다.
  43 ## #이후의 문장은 실행이 안 된다. 메모/도움말 용도로 사용하자

iris dataset

   1 # 다음을 실행 해 보자
   2 iris
   3 dim(iris) # data size(dimension)을 확인해보자.
   4 head(iris) # 첫 6개의 data point만 화면에 출력
   5 tail(iris,5) # 마지막 5개의 data point만 화면에 출력
   6 summary(iris)
   7 boxplot(iris)
   8 plot(iris) # scatter plot
   9 
  10 # Species에 따라 다른 색을 칠하면 보기 편하다
  11 plot(iris, col=c('red','blue','green3')[unclass(iris$Species)])
  12 
  13 # 특정 측정값, 예를 들어 Petal.Length vs. Sepal.Length 만 보고 싶다면,
  14 plot(Sepal.Length ~ Petal.Length, data = iris, col=c('red','blue','green3')[unclass(iris$Species)] )
  15 plot(iris$Petal.Length, iris$Sepal.Length)
  16 
  17 # 한동안 iris 데이타 가지고 놀 것 같으면 미리 선언할 수 있다.
  18 attach(iris) # 앞으로 언급 안 하면 data = iris 라는 뜻임
  19 plot(Petal.Length, Sepal.Length, col=c('red','blue','green4')[unclass(Species)])
  20 plot(Sepal.Length ~ Petal.Length, col=c('red','blue','green4')[unclass(Species)])
  21 detach(iris) # iris 놀이 끝

ChickWeight

병아리 50마리를 대상으로 조사한 다이어트별 성장 속도를 조사한 데이타이다.

과제: ChickWeight 데이타를 이용하여, 다이어트 종류별로 다른 색을 사용하여, 시간 vs 몸무게 그래프를 그려라.

중간고사 문제풀이 in R

   1 library(foreign)
   2 datafile <- file.choose()
   3 
   4 df <- read.spss(datafile, to.data.frame=TRUE)
   5 
   6 colnames(df)
   7 
   8 plot(df$age)
   9 
  10 hist(df$age)
  11 
  12 hist(df$edu)


Class/Statistics/RBasic (2018-10-24 19:25:02에 gehoon가(이) 마지막으로 수정)