Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading