[英]In R how do you take a sample of size n without replacement where length of vector sampling from is <= n
When I run the following I get an error:当我运行以下命令时,出现错误:
sample(c(1,4),5,replace=FALSE)
This is the error:这是错误:
Error in sample.int(length(x), size, replace, prob) :
cannot take a sample larger than the population when 'replace = FALSE'
Is there a way to sample without replacement where it just automatically stops sampling once there is nothing left to sample?有没有一种无需更换的采样方法,一旦没有任何可采样的东西,它就会自动停止采样? The result in this case I would like to be 1,4 or 4,1.
在这种情况下,我希望得到 1,4 或 4,1。
You can do it with an if else
statement.您可以使用
if else
语句来做到这一点。
size_n <- 5
vec <- c(1, 4)
if (length(vec) < size_n) {
sample(vec, length(vec), replace = F)
} else {
sample(vec, size_n, replace = F)
}
If we generalize the question in a way to "take sample size up to n" without replacement, we can do:如果我们将问题概括为“将样本大小增加到 n”而不进行替换,我们可以这样做:
population <- c(1, 4)
samplesize_max <- 5
sample(population, min(length(population), samplesize_max), replace = FALSE)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.