【发布时间】:2018-02-26 22:12:14
【问题描述】:
我有一个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% 左右。我错过了什么?
【问题讨论】: