feng63600
feng63600

Reputation: 183

Matching two columns of different data frames

How to match two columns of different data frame using R? Matched values should align at same position and missing values will be NAs.

Inputs:

df1$A: w x y 
df2$B: x y z 

Expected output data frame:

w  x y NA
NA x y z 

Upvotes: 0

Views: 139

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389325

There should be a better way to represent this but right now I can figure this out. As mentioned in comments by @akrun, you can use match

unique(rbind(cbind(as.character(df1$A), as.character(df2$B[match(df1$A, df2$B)])), 
             cbind(as.character(df2$B), as.character(df1$A[match(df2$B, df1$A)]))))



#    [,1] [,2]
#[1,] "w"  NA  
#[2,] "x"  "x" 
#[3,] "y"  "y" 
#[4,] "z"  NA  

Upvotes: 1

Gaurav
Gaurav

Reputation: 1587

Well this works fine...

df1$B <- ifelse(df1$A %in% df2$B, as.character(df1$A), NA)

df3 <- merge(df1,df2,by='B',all.x = T,all.y = T)

Upvotes: 0

Related Questions