R中的采样错误?
sampling bug in R?
我正在尝试从数值向量中抽取一个元素。
当向量的长度 > 1 时,结果是向量的数字之一,符合预期。但是,当向量包含一个元素时,它会采样介于 0 和该单个数字之间的数字。
例如:
sample(c(100, 1000), 1)
结果是 100 或 1000,但是
sample(c(100), 1)
得到小于 100 的不同数字。
这是怎么回事?
看看示例函数的Details:
"If x has length 1, is numeric (in the sense of is.numeric) and x >= 1, sampling via sample takes place from 1:x"
这是(不幸的)预期行为。参见 ?sample
。 Details 部分的第一行:
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.
幸运的是,Examples
部分提供了建议的修复方法:
# 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
## safer version:
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
当然,您也可以只使用 if
语句:
sampled_x = if (length(my_x) == 1) my_x else sample(my_x, size = 1)
我正在尝试从数值向量中抽取一个元素。
当向量的长度 > 1 时,结果是向量的数字之一,符合预期。但是,当向量包含一个元素时,它会采样介于 0 和该单个数字之间的数字。
例如:
sample(c(100, 1000), 1)
结果是 100 或 1000,但是
sample(c(100), 1)
得到小于 100 的不同数字。
这是怎么回事?
看看示例函数的Details:
"If x has length 1, is numeric (in the sense of is.numeric) and x >= 1, sampling via sample takes place from 1:x"
这是(不幸的)预期行为。参见 ?sample
。 Details 部分的第一行:
If
x
has length 1, is numeric (in the sense of is.numeric) andx >= 1
, sampling via sample takes place from1:x
. Note that this convenience feature may lead to undesired behaviour whenx
is of varying length in calls such assample(x)
. See the examples.
幸运的是,Examples
部分提供了建议的修复方法:
# 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
## safer version:
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
当然,您也可以只使用 if
语句:
sampled_x = if (length(my_x) == 1) my_x else sample(my_x, size = 1)