根据群体内的人口权重进行抽样

时间:2018-02-26 07:59:28

标签: r dplyr sample

我有data.frame,我需要从中提取样本。每年我都需要根据人口权重进行50次观察。以下是一些示例代码:

library(dplyr)

set.seed(1234)
ex.df <- data.frame(value=runif(1000),
                year = rep(1991:2010, each=50),
                group= sample(c("A", "B", "C"), 1000, replace=T)) %>%
mutate(pop.weight = ifelse(group=="A", 0.5,
                         ifelse(group=="B", 0.3,
                                ifelse(group=="C", 0.2, group))))

set.seed(1234)
test <- ex.df %>%
  group_by(year) %>%
  sample_n(50, weight=pop.weight) %>%
  ungroup()

table(test$group)/sum(table(test$group))
    A     B     C 
0.329 0.319 0.352 

小组A应代表约50%,小组B代表30%,C代表大约20%。我错过了什么?

1 个答案:

答案 0 :(得分:1)

设置replace = TRUE。您希望每年进行50次观察,但ex.df每年仅包含50次观察,如果replace = FALSE它只返回不同顺序的相同行。

set.seed(1234)
test <- ex.df %>%
  group_by(year) %>%
  sample_n(50, weight=pop.weight, replace = TRUE) %>%
  ungroup()

table(test$group)/sum(table(test$group))
#     A     B     C 
# 0.509 0.299 0.192 

或者您可以在ex.df中增加每年的观察数。在下面的示例中,我将每年的观察值更改为5000,结果test中的比率看起来合理。

set.seed(1234)
ex.df <- data.frame(value=runif(100000),
                    year = rep(1991:2010, each=5000),
                    group= sample(c("A", "B", "C"), 1000, replace=T)) %>%
  mutate(pop.weight = ifelse(group=="A", 0.5,
                             ifelse(group=="B", 0.3,
                                    ifelse(group=="C", 0.2, group))))

set.seed(1234)
test <- ex.df %>%
  group_by(year) %>%
  sample_n(50, weight=pop.weight) %>%
  ungroup()

table(test$group)/sum(table(test$group))
#     A     B     C 
# 0.515 0.276 0.209