我正在尝试比较两个数据框之间的列名,并在后者数据框中修改列。
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
任何帮助将不胜感激,谢谢!
我们可以使用 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