단순 임의추출과 계통추출

R에서의 표본추출

Richie Cotton

Data Evangelist at DataCamp

단순 임의추출

추첨 통에서 접힌 종이를 뽑는 손.

굴러가는 복권 공.

R에서의 표본추출

커피의 단순 임의추출

행과 열로 배열된 커피 원두.

행과 열로 배열된 커피 원두. 일부는 회색 처리됨.

R에서의 표본추출

R에서 단순 임의추출

set.seed(19000113)
coffee_ratings %>% 
  slice_sample(n = 5)
  total_cup_points variety country_of_origin aroma flavor aftertaste body balance
1            81.00    SL14            Uganda  7.33   6.92       7.17 7.42    7.42
2            85.00 Caturra          Colombia  8.00   7.92       7.75 7.75    7.83
3            85.25 Bourbon         Guatemala  8.00   7.92       7.75 7.92    7.83
4            81.42  Catuai         Guatemala  7.42   7.33       7.08 7.33    7.25
5            82.75 Caturra          Honduras  7.58   7.50       7.42 7.50    7.50
R에서의 표본추출

계통추출

행과 열로 배열된 커피 원두.

행과 열로 배열된 커피 원두. 대각선상 일부만 회색이 아님.

R에서의 표본추출

행 ID 열 추가

library(tibble)
coffee_ratings <- coffee_ratings %>%
  rowid_to_column()
# A tibble: 1,338 x 9
   rowid total_cup_points variety country_of_origin aroma flavor aftertaste  body balance
   <int>            <dbl> <chr>   <chr>             <dbl>  <dbl>      <dbl> <dbl>   <dbl>
 1     1             90.6 NA      Ethiopia           8.67   8.83       8.67  8.5     8.42
 2     2             89.9 Other   Ethiopia           8.75   8.67       8.5   8.42    8.42
 3     3             89.8 Bourbon Guatemala          8.42   8.5        8.42  8.33    8.42
 4     4             89   NA      Ethiopia           8.17   8.58       8.42  8.5     8.25
 5     5             88.8 Other   Ethiopia           8.25   8.5        8.25  8.42    8.33
...
R에서의 표본추출

R에서 계통추출

sample_size <- 5
pop_size <- nrow(coffee_ratings)
1338
interval <- pop_size %/% sample_size
267
R에서의 표본추출

R에서 계통추출 2

row_indexes <- seq_len(sample_size) * interval
267  534  801 1068 1335
coffee_ratings %>% 
  slice(row_indexes)
 # A tibble: 5 x 9
  rowid total_cup_points variety country_of_origin aroma flavor aftertaste  body balance
  <int>            <dbl> <chr>   <chr>             <dbl>  <dbl>      <dbl> <dbl>   <dbl>
1   267             83.9 NA      Colombia           7.92   7.67       7.5   7.58    7.67
2   534             82.9 Bourbon Brazil             7.67   7.58       7.5   7.58    7.5 
3   801             82   Gesha   Malawi             7.5    7.42       7.33  7.33    7.5 
4  1068             80.6 NA      Colombia           7.08   7.25       7     7.08    7.33
5  1335             78.1 NA      Ecuador            7.5    7.67       7.75  5.17    5.25
R에서의 표본추출

계통추출의 문제점

coffee_ratings %>% 
  ggplot(aes(x = rowid, y = aftertaste)) +
  geom_point() +
  geom_smooth()

이 산점도에 패턴이 없어야 계통추출이 안전합니다.

행 ID 대비 뒷맛 점수의 산점도.

R에서의 표본추출

계통추출을 안전하게 하는 방법

shuffled <- coffee_ratings %>%
  slice_sample(prop = 1) %>% 
  select(- rowid) %>% 
  rowid_to_column()
shuffled %>% 
  ggplot(aes(x = rowid, y = aftertaste)) +
  geom_point() +
  geom_smooth()

행을 섞은 뒤 계통추출하면 단순 임의추출과 동일합니다.

데이터셋을 섞은 후 행 ID 대비 뒷맛 점수의 산점도.

R에서의 표본추출

연습해 봅시다!

R에서의 표본추출

Preparing Video For Download...