Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sample() with sample space size = 1

Tags:

r

I have a list of dates that I wish to sample from. Sometimes the sample space will just be a single date e.g. sample("10/11/11",1). The dates are stored as chron objects, so when I have just a single date in my sample space (and only then) sample treats this as a vector (1:date). The documentation for sample points this out:

 If ‘x’ has length 1, is numeric (in the sense of ‘is.numeric’) and
 ‘x >= 1’, sampling _via_ ‘sample’ takes place from ‘1:x’.  _Note_
 that this convenience feature may lead to undesired behaviour when
 ‘x’ is of varying length in calls such as ‘sample(x)’.  See the
 examples.

But I didn't see a way to disable this feature. Is there a workaround or a way to stop it from treating objects of length one as numeric?

like image 241
matt_k Avatar asked Sep 25 '11 18:09

matt_k


1 Answers

The sample documentation recommends this:

resample <- function(x, ...) x[sample.int(length(x), ...)]
like image 53
Aaron left Stack Overflow Avatar answered Nov 06 '22 03:11

Aaron left Stack Overflow