And, surely, regardless of R version: resamp <- function(x,...){if(length(x)==1) x else sample(x,...)}
resamp((1:10),10) # [1] 8 2 10 6 5 4 3 7 9 1 resamp((1:10),1) # [1] 7 resamp((1:10),1) # [1] 4 resamp((1:10),1) # [1] 10 resamp(10,1) # [1] 10 resamp(10,1) # [1] 10 Ted. On 22-Jul-10 20:51:07, Jonathan wrote: > I see.. Thanks! > > On Thu, Jul 22, 2010 at 4:39 PM, Hadley Wickham <had...@rice.edu> > wrote: >> Did you look at the examples in sample? >> >> # sample()'s surprise -- example >> x <- 1:10 >> _ _sample(x[x > _8]) # length 2 >> _ _sample(x[x > _9]) # oops -- length 10! >> _ _sample(x[x > 10]) # length 0 >> >> ## For R >= 2.11.0 only >> resample <- function(x, ...) x[sample.int(length(x), ...)] >> resample(x[x > _8]) # length 2 >> resample(x[x > _9]) # length 1 >> resample(x[x > 10]) # length 0 >> >> Hadley >> >> On Thu, Jul 22, 2010 at 3:31 PM, Jon BR <jonsle...@gmail.com> wrote: >>> Hi All, >>> _ _I'm trying to use the "sample" function within a loop where the >>> vector being sampled from (the first argument in the function) will >>> vary in length and composition. _When the vector is down in size to >>> containing only one element, I run into the "undesired behaviour" >>> acknowledged in the ?sample help file. _I don't want sample(10,1) to >>> return a number from within 1:10, but rather I'd just want it to >>> return 10 every time. >>> >>> Example): >>> >>> >>> Actual: >>>> sample(10,1) >>> [1] 2 >>>> sample(10,1) >>> [1] 9 >>>> sample(10,1) >>> [1] 4 >>> >>> >>> Desired: >>>> sample(10,1) >>> [1] 10 >>>> sample(10,1) >>> [1] 10 >>>> sample(10,1) >>> [1] 10 >>> >>> >>> Perhaps sample is not the appropriate function. _I dunno. _Any >>> thoughts? >>> >>> Regards, >>> Jonathan >>> >>> ______________________________________________ >>> R-help@r-project.org mailing list >>> https://stat.ethz.ch/mailman/listinfo/r-help >>> PLEASE do read the posting guide >>> http://www.R-project.org/posting-guide.html >>> and provide commented, minimal, self-contained, reproducible code. >>> >> >> >> >> -- >> Assistant Professor / Dobelman Family Junior Chair >> Department of Statistics / Rice University >> http://had.co.nz/ >> > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. -------------------------------------------------------------------- E-Mail: (Ted Harding) <ted.hard...@manchester.ac.uk> Fax-to-email: +44 (0)870 094 0861 Date: 22-Jul-10 Time: 22:13:27 ------------------------------ XFMail ------------------------------ ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.