简体   繁体   English

如何根据R中的匹配ID添加列值?

[英]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.

相关问题 如何基于匹配R中的其他列的行值来填充列的值 - How do I fill in values for columns based on matching few other column's row values in R 如何根据满足特定条件的所有行过滤具有匹配列值的多行? [R] - How do I filter multiple rows with matching column values based on all rows meeting a certain condition? [R] 如何根据其他 3 列 [R] 中的匹配值计算我在 1 列中求和的行数? - How do I count the number of rows I have summed values in 1 column based on matching values in 3 other columns [R]? 如何基于R中的匹配值将值列表插入到更大的列中 - How can I insert a list of values into a larger column based on matching values in R 如何根据 R 中的不同范围重新分配列的值? - How do I reassign the values of a column based on different ranges in R? 如何将相应的日期添加到 r 中的单列值? - How do I add corresponding dates to a single column of values in r? 如何根据 R 中匹配 IDS 的两个不同长度的数据帧创建新列 - How to create new column based on two different length dataframe matching IDS in R 根据B列中的日期和R中C列中指定的不匹配值在A列中添加元素 - Add elements in column A based on dates in column B and specified non-matching values in column C in R R:为匹配ID分配值 - R: Assigning values for matching IDs 如何根据R中的分组将单独的列值添加到另一列? - How to add seperate column values to another column based on group by in R?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM