如何在R中查找和求和多列 [英] How to lookup and sum multiple columns in R

查看:159
本文介绍了如何在R中查找和求和多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有2个数据帧,其结构如下:

Suppose I have 2 dataframes structured as such:

组:

P1      P2      P3      P4
123     213     312     231
345     123     213     567

INDIVIDUAL_RESULTS:

INDIVIDUAL_RESULTS:

ID      SCORE
123     23
213     12
312     11
213     19
345     10
567     22

我要添加一个 GROUPS 列,这是它们各自结果的总和:

I want to add a column to the GROUPS which is a sum of each of their individual results:

P1      P2      P3      P4      SCORE
123     213     312     231     65

我尝试使用各种合并技术,但实际上只是一团糟。我觉得有一个我不知道的简单解决方案,非常感谢您提供一些指导!

I've tried using various merge techniques, but have really just created a mess. I feel like there's a simple solution I just don't know about, would really appreciate some guidance!

推荐答案

d1=read.table(text="
P1      P2      P3      P4
123     213     312     231
345     123     213     567",h=T)

d2=read.table(text="
ID      SCORE
123     23
213     12
312     11
231     19
345     10
567     22",h=T)

我将使用 apply match 函数。 Apply将对d1的每一行应用match函数,match将从d1和d2 $ ID(它们的索引)行中找到匹配值,然后在这些索引处获取d2 $ SCORE中的值。最后,我们将它们汇总。

I will be using the apply and match functions. Apply will apply the match function to each row of d1, match will find the matching values from the row of d1 and d2$ID (their indices) and then take the values in d2$SCORE at those indices. In the end we sum them up.

d1$SCORE=apply(d1,1,function(x){
  sum(d2$SCORE[match(x,d2$ID)])
})

和结果

   P1  P2  P3  P4 SCORE
1 123 213 312 231    65
2 345 123 213 567    67

这篇关于如何在R中查找和求和多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆