【发布时间】:2019-01-30 15:38:15
【问题描述】:
我有两个数据框。对于 df1 的某些行,df2 中有匹配的行。现在应该对 df1 的某些列进行操作,以便它们包含它们自己的值与 df2 中的等效值之和。
在以下示例中,列 'count1' 和 'count2' 应该相加,而不是列 'type'。
df1 <- data.frame(id = c("one_a", "two_a", "three_a", "four_a"), type = c(8,7,6,5), count1 = c(1,2,1,NA), count2 = c(NA,0,1,0), id_df2 = c("one", "two", "three", "four"))
df2 <- data.frame(id = c("one", "two", "four"), type = c(8,7,5), count1 = c(0,1,1), count2 = c(0,0,1))
result <- data.frame(id = c("one_a", "two_a", "three_a", "four_a"), type = c(8,7,6,5), count1 = c(1,3,1,1), count2 = c(0,0,1,1))
> df1
id type count1 count2 id_df2
1 one_a 8 1 NA one
2 two_a 7 2 0 two
3 three_a 6 1 1 three
4 four_a 5 NA 0 four
> df2
id type count1 count2
1 one 8 0 0
2 two 7 1 0
3 four 5 1 1
> result
id type count1 count2
1 one_a 8 1 0
2 two_a 7 3 0
3 three_a 6 1 1
4 four_a 5 1 1
有类似的问题,我试图通过将数据框分开并在之后合并它们来找到解决方案。我只是想知道是否有更优雅的方式来做到这一点。我的原始数据集大约有 300 列,因此我正在寻找可扩展的解决方案。
提前致谢 查克莫里斯
【问题讨论】:
标签: r