在 dplyr tidyverse 中按组对不同行数进行采样

Sampling different numbers of rows by group in dplyr tidyverse

我想按组对数据框中的行进行采样。但问题是,我想根据来自另一个 table 的数据对不同数量的记录进行采样。这是我的可重现数据:

df <- data_frame(
  Stratum = rep(c("High","Medium","Low"), 10),
  id = c(1:30),
  Value = runif(30)
)

sampleGuide <- data_frame(
  Stratum = c("High","Medium","Low"),
  Surveys = c(3,2,5)
)

输出应如下所示:

# A tibble: 10 × 2
   Stratum      Value
     <chr>      <dbl>
1     High 0.21504972
2     High 0.71069005
3     High 0.09286843
4   Medium 0.52553056
5   Medium 0.06682459
6      Low 0.38793128
7      Low 0.01285081
8      Low 0.87865734
9      Low 0.09100829
10     Low 0.14851919

这是我的非工作尝试

> df %>% 
+   left_join(sampleGuide, by = "Stratum") %>% 
+   group_by(Stratum) %>% 
+   sample_n(unique(Surveys))
Error in unique(Surveys) : object 'Surveys' not found

还有

> df %>% 
+   group_by(Stratum) %>% 
+   nest() %>% 
+   left_join(sampleGuide, by = "Stratum") %>% 
+   mutate(sample = map(., ~ sample_n(data, Surveys)))
Error in mutate_impl(.data, dots) : 
      Don't know how to sample from objects of class function

似乎 sample_n 要求 size 是一个数字。有什么想法吗?

我只是在寻找 tidyverse 解决方案。 purrr!

加分

是一个类似的问题,但我对接受的答案不满意,因为 IRL 我正在处理的层数很大。

通过 purrr

中的 map2() 解决了这个问题
df %>% 
  nest(-Stratum) %>% 
  left_join(sampleGuide, by = "Stratum") %>% 
  mutate(Sample = map2(data, Surveys, sample_n)) %>% 
  unnest(Sample)