简体   繁体   中英

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.

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)
  }

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM