我正在尝试比较两个数据框之间的列名,并修改后一个数据框中的列。
n = c(0, 1, 0)
s = c(1, 0, 1)
b = c(1, 1, 1)
a = c(0, 0, 0)
c = c(1,3,2)
df1 = data.frame(n, s, b)
df2 = data.frame(n,s,a,c)
如何编写比较/合并df1和df2的语法,使输出如下:
df1 output:
n s b
1 0 1 1
2 1 0 1
3 0 1 1
df2 output:
n s b
1 0 1 0
2 1 0 0
3 0 1 0
感谢您的帮助!
答案 0 :(得分:0)
我们可以使用intersect
和setdiff
#Drop columns from df2 which are not present in df1
df2 <- df2[intersect(names(df1), names(df2))]
#add columns which are present in df1 but not in df2 and assign it to 0
df2[setdiff(names(df1), names(df2))] <- 0
df2
# n s b
#1 0 1 0
#2 1 0 0
#3 0 1 0