I'd like to sample a vector x of length 7 with replacement and sample that vector 10 separate times. I've tried the something like the following but can't get the resulting 7x10 output I'm looking for. This produces a 1x7 vector but I can't figure out to get the other 9 vectors
我想对长度为7的向量x进行替换,然后对这个向量进行10次单独的采样。我已经尝试过类似的东西,但是无法得到我要找的7x10输出。这就产生了一个1x7的向量,但我不能算出其他9个向量。
x <- runif(7, 0, 1)
for(i in 1:10){
samp <- sample(x, size = length(x), replace = T)
}
3 个解决方案
#1
22
This is a very convenient way to do this:
这是一种非常方便的方式:
replicate(10,sample(x,length(x),replace = TRUE))
#2
4
Since you seem to want to sample with replacement, you can just get the 7*10 samples at once (which is more efficient for large sizes):
因为你似乎想要更换样品,你可以一次得到7*10个样品(对于大尺寸更有效率):
x <- runif(7)
n <- 10
xn <- length(x)
matrix(x[sample.int(xn, xn*n, replace=TRUE)], nrow=xn)
# Or slightly shorter:
matrix(sample(x, length(x)*n, replace=TRUE), ncol=n)
The second version uses sample
directly, but there are some issues with that: if x
is a numeric of length 1, bad things happen. sample.int
is safer.
第二个版本直接使用sample,但是有一些问题:如果x是长度为1的数字,就会发生糟糕的事情。sample.int更安全。
x <- c(pi, -pi)
sample(x, 5, replace=T) # OK
x <- pi
sample(x, 5, replace=T) # OOPS, interpreted as 1:3 instead of pi...
#3
2
Looks like you got a suitable answer, but here's an approach that's similar to your first attempt. The difference is that we define samp
with the appropriate dimensions, and then iteratively index into that object and fill it one row at a time:
看起来你得到了一个合适的答案,但这里有一个类似于你第一次尝试的方法。不同之处在于,我们用适当的维度定义samp,然后迭代地索引到该对象中,每次填充一行:
samp <- matrix(NA, ncol = 7, nrow = 10)
for(i in 1:10){
samp[i,] <- sample(x, size = length(x), replace = T)
}
#1
22
This is a very convenient way to do this:
这是一种非常方便的方式:
replicate(10,sample(x,length(x),replace = TRUE))
#2
4
Since you seem to want to sample with replacement, you can just get the 7*10 samples at once (which is more efficient for large sizes):
因为你似乎想要更换样品,你可以一次得到7*10个样品(对于大尺寸更有效率):
x <- runif(7)
n <- 10
xn <- length(x)
matrix(x[sample.int(xn, xn*n, replace=TRUE)], nrow=xn)
# Or slightly shorter:
matrix(sample(x, length(x)*n, replace=TRUE), ncol=n)
The second version uses sample
directly, but there are some issues with that: if x
is a numeric of length 1, bad things happen. sample.int
is safer.
第二个版本直接使用sample,但是有一些问题:如果x是长度为1的数字,就会发生糟糕的事情。sample.int更安全。
x <- c(pi, -pi)
sample(x, 5, replace=T) # OK
x <- pi
sample(x, 5, replace=T) # OOPS, interpreted as 1:3 instead of pi...
#3
2
Looks like you got a suitable answer, but here's an approach that's similar to your first attempt. The difference is that we define samp
with the appropriate dimensions, and then iteratively index into that object and fill it one row at a time:
看起来你得到了一个合适的答案,但这里有一个类似于你第一次尝试的方法。不同之处在于,我们用适当的维度定义samp,然后迭代地索引到该对象中,每次填充一行:
samp <- matrix(NA, ncol = 7, nrow = 10)
for(i in 1:10){
samp[i,] <- sample(x, size = length(x), replace = T)
}