【问题标题】:Replacing specific values in vector with different samples from another vector用来自另一个向量的不同样本替换向量中的特定值
【发布时间】:2016-01-19 17:10:40
【问题描述】:

我有一个带有整数值的向量“a”,由于正在运行的其他代码部分,其中一些可能已变为 0。我想用我拥有的另一个向量“b”中的随机样本替换这个向量中出现的 0。但是,如果“a”中有多个 0 值,我希望它们来自“b”的所有不同样本。比如:

a <- c(1, 2, 3, 0, 0, 0)
b <- 1:100

我希望将“a”的最后三个 0 值替换为“b”中的随机值,但我希望避免使用 1、2 或 3。这些已经在 a 中。

目前,我正在使用 while 循环,所以:

while(0 %in% a) {
  s = sample(1, b)
    while(s %in% a) {
      s = sample(1, b)
    }
  a[a==0][1] = s
}

有没有更好的方法来做到这一点?看起来这个双 while 循环可能需要很长时间才能运行。

【问题讨论】:

    标签: r vector


    【解决方案1】:

    您可以执行以下操作

    indx <- which(!a) # identify the zeroes locations
    # Or less golfed `indx <- which(a == 0)`
    a[indx] <- sample(setdiff(b, a), length(indx)) # replace by a sample from `setdiff(b, a)`
    

    我们没有指定replace = TRUE,所以新的值总是不同的。

    【讨论】:

    • 谢谢!这样干净多了!
    猜你喜欢
    • 1970-01-01
    • 2011-04-23
    • 2021-08-05
    • 1970-01-01
    • 2021-03-01
    • 2021-09-04
    • 2014-04-15
    • 2022-10-02
    • 1970-01-01
    相关资源
    最近更新 更多