繁体   English   中英

从 R 中的分组数据中选择 n 个随机组

[英]Selecting n random groups from grouped data in R

我对由聚集在 160 所学校内的学生组成的数据进行了分组。 我想从该数据集中抽取 30 所学校的随机样本。 我硬编码了一个解决方案(见下文),但是在 R 中是否有包装函数或更快捷的方法来做到这一点? 有点像 sample_n() 或 top_n(),但它们每组返回 n 个观察值,而我想要来自 n 个组的 100% 的观察值。

# First, some example data. Each row represents one student in a given school, and that student's favourite fruit.

df <- tribble(
    ~school_id, ~favourite_fruit,
    #----------#---------------
    1, "apple",
    1, "banana",
    2, "kiwi",
    2, "tomato",
    3, "strawberry",
    3, "cherry",
    4, "orange",
    4, "lime"
)

# My hard-coded solution

school_vector <- df %>% 
    group_by(school_id) %>% 
    select(school_id) %>% 
    count() %>% 
    ungroup() %>% 
    select(school_id) %>% 
    sample_n(2)

df_subset <- df %>% 
    filter(school_id %in% school_vector$school_id) %>% 
    as_tibble()

您可以在filter创建一个school_id样本, school_id其与您当前的%in%逻辑一起使用

df %>% 
  filter(school_id %in% sample(unique(school_id), 2))
# # A tibble: 4 x 2
#   school_id favourite_fruit
#       <dbl> <chr>          
# 1         3 strawberry     
# 2         3 cherry         
# 3         4 orange         
# 4         4 lime   

作为一个函数:

group_samp <- function(df, group_var, n){
  df %>% 
    filter({{group_var}} %in% sample(unique({{group_var}}), n))
}

df %>% 
  group_samp(school_id, 2)
# # A tibble: 4 x 2
#   school_id favourite_fruit
#       <dbl> <chr>          
# 1         1 apple          
# 2         1 banana         
# 3         2 kiwi           
# 4         2 tomato         

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM