[R] using "sample()" for a vector of length 1

Hadley Wickham hadley at rice.edu
Thu Jul 22 22:39:36 CEST 2010


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 <jonsleepy at 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 at 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/



More information about the R-help mailing list