问题描述
我有一组数字 0,1,2,3,4,5,6,7,8,9
我将从那个池中抽取 3 个数字来求和。
我想运行 100 次。
我从池中抽取的 3 个数字必须是唯一的。 即 9,9,9 不能从池中抽取。
我目前的代码是这个。
numbers_in_Box <- c(0,9)
# sample(numbers_in_Box,replace = FALSE)
replicate(n = 100,sample(numbers_in_Box,replace = FALSE),simplify = FALSE)
谢谢
解决方法
问题中的代码没有错,我将更改为 simplify = TRUE
并从设置伪 RNG 种子开始。然后分配 replicate
和 colSums
的输出以获得总和。
set.seed(2021) # Make the results reproducible
numbers_in_box <- c(0,1,2,3,4,5,6,7,8,9)
# sample(numbers_in_box,replace = FALSE)
x <- replicate(n = 100,sample(numbers_in_box,replace = FALSE),simplify = TRUE)
colSums(x)
# [1] 19 18 15 22 10 11 8 14 8 12 18 8 14 10 13 16 12 12 3 15 12
# [22] 10 6 7 17 21 6 23 17 8 8 10 15 15 15 16 11 11 8 7 18 17
# [43] 18 10 8 12 15 17 16 20 14 14 19 17 11 14 12 14 17 19 7 6 19
# [64] 9 21 19 15 19 18 20 15 13 7 13 21 12 21 16 17 18 20 4 13 8
# [85] 17 8 15 15 15 21 14 8 11 15 17 10 20 18 9 9
,
在您的 sum()
中加入 replicate()
调用:
replicate(n = 100,sum(sample(numbers_in_box,replace = FALSE)),simplify = TRUE)
此外,正如@Rui 所建议的,我建议将 simplify
更改为 TRUE
,除非您出于某种原因确实想要列表输出而不是向量。
我们可以使用rerun
library(purrr)
rerun(100,replace = FALSE))