【问题标题】:Match values of column based on other column per groups根据每组的其他列匹配列的值
【发布时间】:2017-04-12 00:23:58
【问题描述】:

我有一个数据框,我想将 ID 的分数值与 New.Score 匹配。

ID 123 在第 1 组的得分为 5,但在第 2 组的得分为 1。而且我只想使用每个组中出现的分数。

这是我的 df:

  Group  ID Score New.ID New.Score
     1 123     5    456         
     1 456     1    789         
     1 789     0    123         
     2 555     1    999         
     2 123     1    123         
     2 999     0    555         

还有我想要的输出:

  Group  ID Score New.ID New.Score
     1 123     5    456         1
     1 456     1    789         0
     1 789     0    123         5
     2 555     1    999         0
     2 123     1    123         1
     2 999     0    555         1

我试过ave

mtch <- function(x) {
  dt[match(x,dt$ID),"Score"]  
}

dt$New.Score <- ave(dt$New.ID, dt$Group, FUN = mtch)

但它给了我 NA 值。

创建df的代码:

Group <- as.factor(c(1, 1, 1, 2, 2, 2))
ID <- as.factor(c(123,456,789, 555, 123, 999))
Score <- c(5,1,0, 1,1,0)
dt <- data.frame(Group, ID, Score, New.ID)

【问题讨论】:

  • 缺少New.ID 列,因此dt &lt;- data.frame(...) 不会运行。

标签: r dataframe match


【解决方案1】:

我们可以使用data.table。将“data.frame”转换为“data.table”(setDT(dt)),按“Group”分组,match“New.ID”和“ID”以获取数字索引并使用它重新排列“ Score' 并将 (:=) 分配给 'New.Score'

library(data.table)
setDT(dt)[, New.Score := Score[match(New.ID, ID)], Group]
dt
#    Group  ID Score New.ID New.Score
#1:     1 123     5    456         1
#2:     1 456     1    789         0
#3:     1 789     0    123         5
#4:     2 555     1    999         0
#5:     2 123     1    123         1
#6:     2 999     0    555         1

【讨论】:

    【解决方案2】:

    您可以使用与我之前的答案 (Set values of column based on other column) 类似的方法,但这次在匹配中使用 interaction。像这样的:

    dt$New.Score <- dt[match(interaction(dt$Group,dt$New.ID) , 
                             interaction(dt$Group,dt$ID)), "Score"]
    
       #   Group  ID Score New.ID New.Score
       # 1     1 123     5    456         1
       # 2     1 456     1    789         0
       # 3     1 789     0    123         5
       # 4     2 555     1    999         0
       # 5     2 123     1    123         1
       # 6     2 999     0    555         1
    

    数据:

    Group <- as.factor(c(1, 1, 1, 2, 2, 2))
    ID <- as.factor(c(123,456,789, 555, 123, 999))
    Score <- c(5,1,0, 1,1,0)
    New.ID <- as.factor(c(456, 789, 123, 999, 123, 555))
    dt <- data.frame(Group, ID, Score, New.ID)
    

    【讨论】:

      猜你喜欢
      • 2022-11-16
      • 1970-01-01
      • 2013-06-20
      • 2019-12-16
      • 2012-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-23
      相关资源
      最近更新 更多