Reputation: 6399
I have a variable that contains some numbers which change throughout the program.
e.g.:
a<-c(1,2,4,6,5)
I would like to take a fixed number of samples (3) every time:
sample(a,3,replace=FALSE)
In some cases it could be that a < 3 in such cases I get the following error:
Error in sample(a, 3, replace = FALSE, prob = c(weights)) : cannot take a sample larger than the population when 'replace = FALSE'
Is there a way to sample such that if a<3 than it takes as much as it can? For example, if a=2 and sample size should be 3 then it only takes 2
Upvotes: 2
Views: 482
Reputation: 70623
You could add a control if
statement before you sample to check the length of your a
and adjust my.size
accordingly.
> my.size <- 3
> a <- 1:3
> if (length(a) <= 3) {
> my.size <- length(a)
> message(paste("Sampling size was reduced to ", my.size, ".", sep = ""))
> }
Sampling size was reduced to 2.
> my.size
[1] 2
> sample(a, size = my.size, replace=FALSE)
[1] 1 2
Upvotes: 1