首页 > 解决方案 > 双循环以获取 R 中的数据帧(tidyverse)

问题描述

我想sample(1:11, 1)在 5 个不同的回合中重复 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

标签: rdataframeloopstidyverselapply

解决方案


我们可以用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)

推荐阅读