【问题标题】:Sample according to population weights within groups根据组内总体权重进行抽样
【发布时间】: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% 左右。我错过了什么?

【问题讨论】:

    标签: r dplyr sample


    【解决方案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 
    

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 2015-06-14
      • 2017-06-05
      • 2021-09-20
      • 2021-10-19
      • 2020-05-31
      • 2020-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多