管道中的 Dplyr 下采样

Dplyr downsample in pipeline

我有这样的小毛病:

tibble(a = c(1,2,3,4,5), b = c(1,1,1,2,2))

我想通过 "b" 列对数据进行随机下采样,如下所示:

tibble(a = c(1,3,4,5), b = c(1,1,2,2))

如何在不更改 tibble 的数据类型的情况下完全在 Dplyr 管道中执行此操作?

这将获得最小的组大小(按 b 分组),并从每个组中抽取那么多元素。不清楚这是否是您想要的。

如果你的小标题叫 df

df %>% 
  group_by(b) %>% 
  add_count %>% 
  slice(sample(row_number(), min(.$n))) %>% 
  select(-n)