Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
822 views
in Technique[技术] by (71.8m points)

r - Using sample() with sample space size = 1

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The sample documentation recommends this:

resample <- function(x, ...) x[sample.int(length(x), ...)]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...