[英]How do I add column values based on matching IDs in R?
I have two data frames: 我有两个数据框:
A: A:
ID Var1 Var2 Var3
1 0 3 4
2 1 5 0
3 1 6 7
B: B:
ID Var1 Var2 Var3
1 2 4 2
2 2 1 1
3 0 2 1
4 1 0 3
I want to add the columns from A and B based on matching ID's to get data frame C, and keep row 4 from B (even though it does not have a matching ID from A): 我想根据匹配的ID从A和B添加列以获取数据帧C,并保留B的第4行(即使它没有来自A的匹配ID):
ID Var1 Var2 Var3
1 2 7 6
2 3 6 1
3 1 8 8
4 1 0 3
rbind
and aggregate
by ID
: rbind
并按ID
aggregate
:
aggregate(. ~ ID, data=rbind(A,B), sum)
# ID Var1 Var2 Var3
#1 1 2 7 6
#2 2 3 6 1
#3 3 1 8 8
#4 4 1 0 3
In data.table
you can similarly do: 在
data.table
您可以类似地执行以下操作:
library(data.table)
setDT(rbind(A,B))[, lapply(.SD, sum), by=ID]
And there would be analogous solutions in dplyr and sql or whatever else. 在dplyr和sql或其他工具中将有类似的解决方案。 Bind the rows, group by ID, sum.
绑定行,按ID,总和分组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.