gpt4 book ai didi

bool 向量的随机样本

转载 作者:行者123 更新时间:2023-12-02 17:51:15 25 4
gpt4 key购买 nike

我有一个输入向量 vi与 bool 值。我想随机抽取一个大小为 n 的样本来自值为真的向量,所以最终向量 vf具有这些属性

  1. 向量的长度相等 length(vf) == length(v0)

  2. vfn真值 n==sum(vf)

  3. vf 中的真实值不能超过v0中的那些n <= sum(v0)

  4. vf 中的所有真值在 vi 中也是如此

向量表示数据框中行的选择,这实现了分层样本。到目前为止,我想出了如何使用 which()获取行号,使用 sample()获取随机样本,但最后一部分是重新创建 bool 向量。可能有更优雅的方式?

例如:

n <- 1

v0 <- c(T,T,F,F)

vf <- c(T,F,F,F)

最佳答案

这是一种解决方案:

# Make up some vector v0 and choose n
v0 <- rep(c(F,T,F), 5)
n <- 3


# The actual code
x <- which(v0)
vf <- logical(length(v0))
vf[x[sample.int(length(x), n)]] <- TRUE


# Finally validate the result
identical(length(vf), length(v0)) # TRUE
all(v0[vf]) # TRUE
sum(vf) == n # TRUE

关于 bool 向量的随机样本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7745065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com