[R] Size argument in sample function

Marc Schwartz marc_schwartz at me.com
Fri Jun 17 20:03:09 CEST 2011


Just use lapply():

set.seed(1)
x <- rnorm(20)

> lapply(1:3, function(i) sample(x, i))
[[1]]
[1] -0.6264538

[[2]]
[1] -0.3053884 -2.2146999

[[3]]
[1] -2.21469989 -0.30538839 -0.04493361


HTH,

Marc Schwartz


On Jun 17, 2011, at 12:53 PM, Daniel Malter wrote:

> I am sure there is a more elegant version of doing this. But this works:
> 
> x<-rnorm(20)
> y<-matrix(1:5) #number of points to sample
> f<-function(z){sample(x,z)}
> apply(y,1,f)
> 
> Just adjust y to your liking.
> 
> HTH,
> Daniel
> 
> 
> alfredo wrote:
>> 
>> Hi All,
>> 
>> I'd like to randomly sample a vector N times, where each successive random
>> sample increases in size. I have realised that the function sample does
>> not take vectors for arguments. For example,
>> 
>> x<-rnorm(20,0,1)
>> sample(x,c(1,2,3)) ## will only return one random sample of size 1. 
>> 
>> The trick seems to be getting past the size argument of the function. I've
>> tried different things without success. Any help would be most
>> appreciated!
>> 
>> Thanks,
>> 
>> A



More information about the R-help mailing list