双循环以获取 R 中的数据帧(tidyverse)

Double looping to get a dataframe in R (tidyverse)

我想在 5 个不同的回合中重复 sample(1:11, 1) 6 次。在最终输出中,我想要一个 data.frame,其中每一轮都是一行(见下文)。

这是否可以在 tidyverse(例如 purrr::map_df)或 BASE R 中实现?

round1 4 5 6 7 8 9
round2 3 2 1 4 4 1
round3 5 4 2 2 1 1
round4 7 7 7 7 7 1
round5 1 8 8 8 8 1

我们可以使用replicate

t(replicate(5, sample(1:11, 6, replace = TRUE)))

正如@thelatemail 提到的,我们只能sample一次并将数据放入矩阵中。

nr <- 5
nc <- 6
matrix(sample(1:11, nr * nc, replace = TRUE), nr, nc)

为什么不用lapply对6个元素采样5次。示例中的替换标志提供了多次拉取相同数字的机会。

 data.frame(do.call(rbind, lapply(1:5,function(x) sample(1:11, 6, replace=T)))

正如 OP 询问的那样 purrr,这里有一个 tidyverse 解决方案,它获取预期输出中指定的行名称:

library(tidyverse)

rounds <- paste0("round", 1:5) 

rounds %>% 
  setNames(rounds) %>% 
  map_dfc(~sample(1:11, 6, replace = TRUE)) %>% 
  t()

       [,1] [,2] [,3] [,4] [,5] [,6]
round1    1   11   10    6    5   10
round2    9    2    3    3    2   10
round3    8    8    2   11    6    7
round4    1    7    8    6   11   10
round5    1    7    7    3    1    8