我有一份我希望从中抽样的日期列表。有时,样本空间只是一个日期,例如样品( “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.
但我没有看到禁用此功能的方法。是否有一种解决方法或方法来阻止它将长度为1的对象视为数字?
答案 0 :(得分:12)
sample
文档建议:
resample <- function(x, ...) x[sample.int(length(x), ...)]
答案 1 :(得分:5)
我会将它包装在if
语句中,或将其包装在另一个函数中。例如:
mysample <-
function(x, size, replace=FALSE, prob=NULL)
{
if(length(x)==1)
return(rep(x, size))
sample(x, size, replace, prob)
}