按行和列重叠合并2个数据帧 [英] Merge 2 data frames by row and column overlap

查看:84
本文介绍了按行和列重叠合并2个数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将2个数据帧加法合并,以使

I would like to merge 2 data frames additively such that

      taxonomy A B C
1          rat 0 1 2
2          dog 1 2 3
3          cat 2 3 0

      taxonomy A D C
1          rat 0 1 9
2        Horse 0 2 6
3          cat 2 0 2

产生

      taxonomy A B C  D
1          rat 0 1 11 1
2        Horse 0 0 6  2 
3          cat 4 3 2  0
4          dog 1 2 3  0

我尝试过汇总,合并,应用,ddply ....没有成功...这将在具有数百行和几列的2个数据帧上完成

I've tried aggregate, merge, apply, ddply.... with no success...this will be done on 2 data frames with a couple hundred rows and columns

推荐答案

相当于@avid_useR答案的data.table.

The data.table equivalent of @avid_useR's answer.

library(data.table)
rbindlist(list(df1, df2), fill = TRUE)[, lapply(.SD, sum, na.rm = TRUE), by = taxonomy]
#   taxonomy A B  C D
#1:      rat 0 1 11 1
#2:      dog 1 2  3 0
#3:      cat 4 3  2 0
#4:    Horse 0 0  6 2

这篇关于按行和列重叠合并2个数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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