这是 How to lookup and sum multiple columns in R 的后续内容:
我有 3 个数据框:
群组:
P1 P2 P3 P4
"Joe" "Sally" "A.J." "Mary"
"Cory" "Joe" "Sally" "Katy"
姓名:
ID NAME
123 "Joe"
213 "Sally"
312 "A.J."
231 "Mary"
345 "Cory"
567 "Katy"
个人结果:
ID SCORE
123 23
213 12
312 11
231 19
345 10
567 22
我的目标是在 Groups
中创建一个新列,其中 SCORE
列是组中每个结果的总和
P1 P2 P3 P4 SCORE
"Joe" "Sally" "A.J." "Mary" 65
按照上面引用的问题中的答案示例,我尝试了以下操作
groups$score = apply(groups, 1, function(x){
sum(Individual_Results$SCORE[match(match(x, Names$Name), Individual_Results$ID)])
})
不幸的是,结果是创建新列,但每个分数的结果都是NA
。
如果我了解如何正确使用 apply
和 match
,那么我要做的是将函数应用
到每个行,将 x
(Name
)作为参数传递给第一个 match
函数,以获取 ID
然后将返回的 ID
与第二个 match
进行匹配以获得分数 - 将每行的所有分数相加。
我认为我已经非常接近了,但还不够。感谢任何帮助!
最佳答案
这样就可以了。
请注意,您不需要data.table
。我只是用它来使示例可重现
require(data.table)
Groups <- data.frame(fread('"P1","P2","P3","P4"
"Joe","Sally","A.J.","Mary"
"Cory","Joe","Sally","Katy"'))
Names <- data.frame(fread('ID,NAME
123,"Joe"
213,"Sally"
312,"A.J."
231,"Mary"
345,"Cory"
567,"Katy"'))
Individual_Results <- data.frame(fread('ID,SCORE
123,23
213,12
312,11
231,19
345,10
567,22'))
Groups$SCORE <- apply(Groups, 1, function(x){
sum(Individual_Results$SCORE[match(Names$ID[match(x, Names$NAME)], Individual_Results$ID)])
})
# Inspect groups:
Groups
# P1 P2 P3 P4 SCORE
# 1 Joe Sally A.J. Mary 65
# 2 Cory Joe Sally Katy 67
关于r - R 中的嵌套匹配函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58460249/