2

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

4

2 回答 2

8
sample(a, min(length(a), 3), replace=FALSE)
于 2012-12-20T14:46:32.340 回答
1

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
于 2012-12-20T14:43:30.150 回答