首页 > 解决方案 > Comparing Dataframe column names in R

问题描述

I am trying to compare the column names between two dataframes and modify the columns in the latter dataframe.

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)

How do I write a syntax comparing/merging df1 and df2 such that the outputs are as follows:

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

Any help is appreciated thank you!

标签: rdataframemergecompare

解决方案


我们可以使用intersectsetdiff

#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

推荐阅读