R Basic

기본 of 기본

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

trees dataset

   1 # trees란 무엇인가!
   2 ?trees
   3 
   4 # trees 데이타를 화면에 띄워보자
   5 trees # 혹은 print(trees)
   6 str(trees)
   7 table(trees)
   8 
   9 # data size(dimension)을 확인해보자.
  10 dim(trees)
  11 
  12 # 31 x 3 개의 숫자를 한번에 보려니 눈에도 안 들어오고 의미없다. 일부만 화면에 띄워보자.
  13 head(trees) # 첫 6개의 data point만 화면에 출력
  14 head(trees,10) # 첫 10개의 data point만 화면에 출력
  15 tail(trees,4) # 마지막 4개의 data point만 화면에 출력
  16 
  17 # 데이타의 평균, 최상값, 최소값, 중간값, 상위 25% 값, 하위 25% 값을 보고 싶다면,
  18 summary(trees)
  19 
  20 # 나무 높이의 평균, 최상값, 최소값, 중간값, 상위 25% 값, 하위 25% 값을 따로 보고 싶다면,
  21 mean(trees$Height) # mean(trees) 은 어떤 결과가 나오나?
  22 max(trees$Height) # max(trees) 은 어떤 결과가 나오나?
  23 min(trees$Height) # min(trees) 은 어떤 결과가 나오나?
  24 quantile(trees$Height) # quantile(trees) 은 어떤 결과가 나오나?

숫자보다 그림이 데이타를 한눈에 파악하기 편하다.

   1 boxplot(trees)
   2 
   3 # 통계 계산값 말고, 모든 data point를 다 xy 평면에 찍어줘
   4 plot(trees)
   5 
   6 # 특별히 Girth 대비 Volume만 따로 xy 평면에 보여주되, xy 둘다 log scale 로 보겠어
   7 plot(Volume ~ Girth, data = trees, log = "xy")
   8 # trees 데이타의 컬럼 이름을 지정하는 방법
   9 plot(trees$Girth, trees$Volume, log = "xy")
  10 # trees 데이타의 컬럼 번호를 지정하는 방법
  11 plot(trees[,1], trees[,3], log = "xy")
  12 
  13 trees[c(3:10), c(1,3)]
  14 plot(trees[c(3:10), c(1,3)])

Tip:

궁극의 Tip:

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 몸무게 그래프를 그려라.

Birthday Paradox

Birthday Paradox: 23명이 모이면 그 안에 생일이 같은 사람이 존재할 확률은 50% 이상이다.

계산해보자

   1 person <- 23
   2 odd <- 1.0
   3 
   4 for (n in 2:person) {
   5   odd = odd * (366 - n) / 365
   6   print((1-odd) * 100)
   7 }

참고로 python이라면 이렇게 쓴다

   1 person = 23
   2 odd = 1.0
   3 
   4 for n in range(2,person+1):
   5     odd = odd * (366 - n)/365
   6     print (1-odd) * 100

수학이 어려우면 무식한 시뮬레이션으로 알아볼 수도 있다 (brute force algorithm)

   1 birthday <- function(nPeople = 23, num = 1000) {
   2   data <- rep(NA,num)
   3   for (i in 1:num) {
   4     thisGroup <- sample(1:365, nPeople, replace = TRUE)
   5     data[i] <- sum(duplicated(thisGroup)) > 0
   6   }
   7   print(sum(data)/num)
   8 }
   9 birthday()
  10 birthday(nPeople = 30, num =10000)

for-loop으로 구성된 코드는 가독성(human readability)은 좋지만 처리속도는 불리하다.

   1 birthdays <- sapply(1:10000, function(x){sample(1:365, 23, replace = TRUE)})
   2 sum(sapply(1:10000, function(x) sum(duplicated(birthdays[,x])) > 0))
   3 
   4 # nice one-liner
   5 birthdays <- function(x){sum(duplicated(sample(1:365, 23, replace = TRUE)))>0}
   6 sum(sapply(1:10000, birthdays))

과제: 어느 모임에서 생일이 같은 사람이 있을 확률이 99% 이상이 되려면 모임이 몇 명이어야 될까?


Class/Statistics/RBasic (2018-10-29 19:20:07에 gehoon가(이) 마지막으로 수정)