【问题标题】:Sampling from a data.frame while controlling for a proportion [stratified sampling]在控制比例的同时从 data.frame 中采样 [分层采样]
【发布时间】:2015-06-04 07:54:43
【问题描述】:

我有以下数据集

id1<-c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)
status<-c(1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2)
df<-data.frame(id1,status)

df 中,我观察到的status 中有40% 是“2”。 我正在寻找一个函数来从df 中提取 10 个观察值的样本,同时保持上述比例。

我已经看过stratified random sampling from data frame in R,但不是在谈论比例。

【问题讨论】:

    标签: r sampling


    【解决方案1】:

    你可以试试我的“splitstackshape”包中的stratified函数:

    library(splitstackshape)
    stratified(df, "status", 10/nrow(df))
    #     id1 status
    #  1:   5      1
    #  2:  12      1
    #  3:   2      1
    #  4:   1      1
    #  5:   6      1
    #  6:   9      1
    #  7:  16      2
    #  8:  17      2
    #  9:  18      2
    # 10:  15      2
    

    或者,使用来自“dplyr”的sample_frac

    library(dplyr)
    
    df %>%
      group_by(status) %>%
      sample_frac(10/nrow(df))
    

    这两种方法都将采用与原始分组变量成比例的分层样本(因此使用10/nrow(df),或者等效地使用0.5)。

    【讨论】:

    • 快速提问@Ananda Mahto。这种抽样方法会被替换吗?
    • @AliCivil,您可以使用替换参数指定它(默认=FALSE - 请参阅函数的帮助)。如需更换,请添加replace=TRUEstratified(df, "status", 10/nrow(df), replace=TRUE)
    猜你喜欢
    • 2020-02-12
    • 2022-09-30
    • 2015-11-21
    • 2017-04-05
    • 2021-07-11
    • 2021-02-01
    • 2018-01-24
    • 1970-01-01
    相关资源
    最近更新 更多