【问题标题】:Return values with matching conditions in r在 r 中返回具有匹配条件的值
【发布时间】:2020-01-02 21:58:33
【问题描述】:

我想根据评分标准在另一列中返回具有匹配条件的值。如果变量中没有切割分数,我想获取最接近的较大值。这是数据集的快照:

ids <- c(1,2,3,4,5,6,7,8,9,10)
scores.a <- c(512,531,541,555,562,565,570,572,573,588)
scores.b <- c(12,13,14,15,16,17,18,19,20,21)
data <- data.frame(ids, scores.a, scores.b)
> data
   ids scores.a scores.b
1    1      512       12
2    2      531       13
3    3      541       14
4    4      555       15
5    5      562       16
6    6      565       17
7    7      570       18
8    8      572       19
9    9      573       20
10  10      588       21

cuts <- c(531, 560, 571)

我想获取与第一个分数对应的score.b值,即13。然后,抓取第二切(560)分数对应的 score.b 值但不在 score.a 中,所以我想获取 score.a 值562(最接近560),对应的值为16。最后,对于第三切分数(​​571),我想得到 19,这是与第三切分数最接近的值(572)的对应值。

这是我想要的。

       scores.b
cut.1  13
cut.2  16
cut.3  19

有什么想法吗? 谢谢

【问题讨论】:

    标签: r subset


    【解决方案1】:

    我们可以使用滚动连接

    library(data.table)
    setDT(data)[data.table(cuts = cuts), .(ids = ids, cuts, scores.b), 
              on = .(scores.a = cuts), roll = -Inf]
    #   ids cuts scores.b
    #1:   2  531       13
    #2:   5  560       16
    #3:   8  571       19
    

    或者另一个选项是 findInterval from base R 在更改标志并采用 reverse 之后

    with(data, scores.b[rev(nrow(data) + 1 - findInterval(rev(-cuts), rev(-scores.a)))])
    #[1] 13 16 19
    

    【讨论】:

    • 这很好用@akrun,感谢您的快速回复!
    • findInterval 选项很简洁,尽管我相信它将依赖于被排序的数据。我的尝试类似 - data$scores.b[match(seq_along(cuts), findInterval(data$scores.a, cuts))]
    • @thelatemail 看起来更好。您可以添加一个单独的解决方案,因为这是切换参数
    • @thelatemail 看起来您在上面的 cmets 中发布了与我相同的答案。如果您发布此解决方案,请告诉我,我将删除我的解决方案
    • 嗨@akrun,如果我在上面的陈述中进行如下更改,您的建议是什么:“如果变量中没有切割分数,我想获取最接近的较大的值第二次切割和最接近的较小值第三次切割得分。我想得到:13, 16, 18 而不是 13,16,19
    【解决方案2】:

    这不会删除其他列,但可以更好地说明正确的结果

    df1 <- data[match(seq_along(cuts), findInterval(data$scores.a, cuts)), ]
    rownames(df1) <- paste("cuts", seq_along(cuts), sep = ".")
    
    > df1
           ids scores.a scores.b
    cuts.1   2      531       13
    cuts.2   5      562       16
    cuts.3   8      572       19
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-07
      • 2019-03-10
      • 1970-01-01
      • 2020-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多