来自不同长度向量的样本(包括 1 个) [英] Sample from vector of varying length (including 1)
问题描述
我有一个长度可变的向量,有时长度为 1.
I have a vector with varying length, which can sometimes be of length 1.
我想从这个向量中采样,如果它的长度是 1,它总是采样那个 1 个数字.
I would like to sample from this vector such that if its length is 1 it always samples that 1 number.
sample()
不会这样做,因为当样本大小为 1 时,它会从 1 到数字进行采样.
sample()
won't do this because it samples from 1 to the digit when sample size is 1.
推荐答案
这是一个文档化的功能:
This is a documented feature:
如果 x
的长度为 1
,则为 numeric
(在 is.numeric
的意义上)和 x >= 1
,从1:x
开始采样.请注意,当 x
在诸如 sample(x)
之类的调用中具有不同的长度时,此便利功能可能会导致不良行为.
If
x
has length1
, isnumeric
(in the sense ofis.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)
.
另一种方法是编写自己的函数来避免该功能:
An alternative is to write your own function to avoid the feature:
sample.vec <- function(x, ...) x[sample(length(x), ...)]
sample.vec(10)
# [1] 10
sample.vec(10, 3, replace = TRUE)
# [1] 10 10 10
一些具有类似行为的函数列在 seq 与 seq_along.什么时候使用 seq 会导致意想不到的结果?
Some functions with similar behavior are listed under seq vs seq_along. When will using seq cause unintended results?
这篇关于来自不同长度向量的样本(包括 1 个)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!