gpt4 book ai didi

r - 使用 dplyr 在 r 中对一组内进行多次采样

转载 作者:行者123 更新时间:2023-12-03 08:20:44 27 4
gpt4 key购买 nike

我正在尝试在每个组中挑选样本:

df <- data.frame(ID=c(1,1,1,2,2,2), score=c(10,20,30,40,50,60))

ID score
1 1 10
2 1 20
3 1 30
4 2 40
5 2 50
6 2 60

df %>% group_by(ID) %>% sample_n(2)

ID score
1 1 20
2 1 30
3 2 50
4 2 40

但我想为每个 ID 执行n 多次,例如 2 次以获得如下内容:

     ID score sample_num
1 1 20 1
2 1 30 1
3 1 20 2
4 1 10 2
5 2 50 1
6 2 40 1
7 2 60 2
8 2 40 2

每个 sample 组都应该在没有替换的情况下完成。有没有办法在 dplyr 中做到这一点?我能想到的长方法是做一个for循环,每次迭代创建一个df,然后在最后将所有df组合在一起。

最佳答案

如果您必须执行N次,请执行此操作

  • 创建一个变量 N
  • map_dfr 将迭代其第一个参数,即 seq_len(N) ,执行您手动执行的操作,更改另一个变量,该变量将存储 的相应值seq_len(N) 即每次迭代的 lambda 公式中的 .x
  • 最终结果将编译在数据框中,因为我们使用 mapmap_dfr 变体
df <- data.frame(ID=c(1,1,1,2,2,2), score=c(10,20,30,40,50,60))

library(tidyverse)
N <- 7
map_dfr(seq_len(N), ~df %>% group_by(ID) %>% sample_n(2) %>%
mutate(sample_no = .x))
#> # A tibble: 28 x 3
#> # Groups: ID [2]
#> ID score sample_no
#> <dbl> <dbl> <int>
#> 1 1 20 1
#> 2 1 10 1
#> 3 2 60 1
#> 4 2 50 1
#> 5 1 30 2
#> 6 1 10 2
#> 7 2 60 2
#> 8 2 40 2
#> 9 1 10 3
#> 10 1 20 3
#> # ... with 18 more rows

reprex package 于 2021 年 6 月 11 日创建(v2.0.0)

关于r - 使用 dplyr 在 r 中对一组内进行多次采样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67939371/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com