使用样本空间大小= 1的sample()

时间:2021-02-10 20:11:29

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:

我有一份我希望从中抽样的日期列表。有时,样本空间只是一个日期,例如样品( “10/11/11”,1)。日期存储为chron对象,因此当我在样本空间中只有一个日期(并且只有那时)时,样本将其视为向量(1:date)。样本文档指出了这一点:

 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?

但我没有看到禁用此功能的方法。是否有一种解决方法或方法来阻止它将长度为1的对象视为数字?

2 个解决方案

#1


12  

The sample documentation recommends this:

示例文档建议:

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

#2


5  

I would wrap it in an if statement, or wrap it inside another function. For example:

我会将它包装在if语句中,或将其包装在另一个函数中。例如:

mysample <-
function(x, size, replace=FALSE, prob=NULL)
{
  if(length(x)==1)
    return(rep(x, size))

  sample(x, size, replace, prob)
}

#1


12  

The sample documentation recommends this:

示例文档建议:

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

#2


5  

I would wrap it in an if statement, or wrap it inside another function. For example:

我会将它包装在if语句中,或将其包装在另一个函数中。例如:

mysample <-
function(x, size, replace=FALSE, prob=NULL)
{
  if(length(x)==1)
    return(rep(x, size))

  sample(x, size, replace, prob)
}