dplyr样本(按值组)

威尔卡

我想使用dplyr根据分组值制作样本:

我试过了

 id <- c(1, 1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 6, 7, 8, 8, 8, 8, 8)

 id <-  as.data.frame(id)

 sample <- id %>%
   group_by(id) %>%
   sample_n(2, replace = FALSE) %>%
   ungroup(id)

sample

预期结果(n个样本= 2):

1, 1, 1, 2

要么

1, 1, 1, 3, 3

要么

5, 5, 5, 6, 6

等等

我有一个错误:

Error: `size` must be less or equal than 1 (size of data), set `replace` = TRUE to use sampling with replacement
阿克伦

也许这有帮助

id %>% 
  distinct(id) %>% 
  sample_n(2, replace = FALSE) %>% 
  inner_join(id, .)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章