采样 5 次并求和,有放回

Sample 5 times and sum, with replacement

我正在尝试通过稍微扭曲的替换来进行采样。我想对列表、向量等进行采样 5 次并求和。并替换5个采样值,重复1000次

x<- 1:1000
samp <- matrix(NA, ncol = 1, nrow = 1000)
for(i in length(x)){
samp[i,] <- sum(sample(x,5,replace = TRUE))}

我不明白为什么这个循环不起作用

您错过了 length(x) 前面的 1:(即从 1 到 x 的长度加 1)。你的代码应该是这样的:

x<- 1:1000
samp <- matrix(NA, ncol = 1, nrow = 1000)
for(i in 1:length(x)){
  samp[i,] <- sum(sample(x,5,replace = TRUE))}

哪个效果很好:

> str(samp)
 int [1:1000, 1] 2715 2312 3180 1364 2851 2429 2888 2381 2772 2317 ...

此外,for-loops 因在 R 中运行缓慢而声名狼藉,因此您可能需要考虑其他循环方式,例如使用 C++ 方式(例如)replicate像这样:

定义函数:

myfunc <- function(x) {
  sum(sample(x,5,replace = TRUE))
}

然后像这样使用它:

x <- 1:1000
mymat <- matrix(replicate(1000, myfunc(x)), ncol=1)

> str(mymat)
 int [1:1000, 1] 2481 2236 2492 1759 1905 3243 2606 2624 3013 2309 ...