如何将R中的2个数据帧合并为这样

时间:2015-07-25 22:58:19

标签: r merge dataframe

如何从数据帧A和B获取数据帧C?

数据框C:

Type CountA CountB
A    40     40
B    50
C    35
D           20

数据框A:

Type Count 
A    40 
B    50 
C    35

数据框B:

Type Count
A    40
D    20

1 个答案:

答案 0 :(得分:0)

merge(a, b, all = TRUE, by = "Type")

如果您想要显示的命名,

setNames(merge(a, b, all = TRUE, by = "Type"), c("Type", "CountA", "CountB"))

请注意,您将获得NA缺失值。具有空值将要求您将它们强制转换为字符串。

merged <- setNames(merge(a, b, all = TRUE, by = "Type"), c("Type", "CountA", "CountB"))
ccol <- c("CountA", "CountB")
merged[ccol] <- lapply(merged[ccol], function(x) {
  x[is.na(x)] <- ""
  x
})