R中的随机采样:限制重复次数

时间:2019-02-10 14:56:19

标签: r

我在R中具有以下向量:z = c(1,3,5,7,9,11)。

我希望一次从此向量中随机采样4个元素,但要确保不超过2个元素重复。即

sample(z,4,replace=T) = (1,1,3,11)
sample(z,4,replace=T) = (1,5,5,9)

但不是

sample(z,4,replace=T) = (1,1,1,11)

以此类推。

我该怎么做?

谢谢!

1 个答案:

答案 0 :(得分:0)

@MichaelChirico的回答似乎正确。我用一些解释将其重写,

z <- c(1,3,5,7,9,11)  
sample(
  rep(z, 
      times = 2L  # times = 2L doubles the vector z
      ),
  size = 4L,  # it determines the number of items to choose
  replace = FALSE  # this is default but it makes no more than 2 elements repeated
)  

通过在您自己的代码“ sample(z,4,replace = T)”中为 replace 参数选择FALSE,
它根本不返回任何重复。

相关问题