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.
CodePudding user response:
You can do it with an if else
statement.
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)
}
CodePudding user response:
If we generalize the question in a way to "take sample size up to n" without replacement, we can do:
population <- c(1, 4)
samplesize_max <- 5
sample(population, min(length(population), samplesize_max), replace = FALSE)