【问题标题】:Generating a vector with values based conditionally from other vectors有条件地从其他向量生成具有值的向量
【发布时间】:2017-06-21 18:27:12
【问题描述】:

假设我有两个向量。

a <- c(1,5)
b <- c(2,3,4,6) 

我想从这两个向量中创建一个向量,使得“a”中新向量中的位置为红色,“b”为蓝色,结果

c <- c('red','blue','blue','blue','red','blue')

我认为使用 rep 可能会有所帮助,但例如基于 ab 的 rep 中的某种 ifelse?

【问题讨论】:

    标签: r


    【解决方案1】:

    怎么样

    cols <- rep(NA,length(a)+length(b))
    cols[a] <- "red"
    cols[b] <- "blue"
    
    cols
    #  [1] "red"  "blue" "blue" "blue" "red"  "blue"
    

    【讨论】:

    • 太棒了!我正在努力弄清楚这一点。谢谢。
    【解决方案2】:

    这是stack 的选项。在listmgetstack 中获取vector 对象以创建data.frametransform 的“ind”列到factorlabels 为“红色”、“蓝色” ,在ordering 'values' 之后获取'ind'。

    d1 <- transform(stack(mget(c('a', 'b'))), ind = factor(ind, labels = c('red', 'blue')))
    as.character(d1$ind[order(d1$values)])
    #[1] "red"  "blue" "blue" "blue" "red"  "blue"
    

    正如@Frank 所说,使用这种方法,可以sorted out 2 个以上的向量

    【讨论】:

    • 值得注意的是:这是迄今为止发布的唯一可以完全扩展到更多向量(除了 a 和 b 这两个)的方法。
    【解决方案3】:

    与@MattTyers 简洁的解决方案相比,可能是更通用的解决方案:

    cols <- sort(c(a,b))
    cols[cols %in% a] <- "red"
    cols[cols %in% b] <- "blue"
    cols
    # [1] "red"  "blue" "blue" "blue" "red"  "blue"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多