0

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 
Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
feng63600
  • 183
  • 1
  • 2
  • 13

2 Answers2

1

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  
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

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)

Gaurav
  • 1,597
  • 2
  • 14
  • 31
  • I think the ifelse is not needed, `merge(df1, df2, by.x = 'A', by.y = 'B', all = TRUE)` will do just fine as far i can judge atm. – Jaap May 19 '16 at 06:49
  • @ProcrastinatusMaximus Well this just gives me (A: w x y z) as a single column dataframe output... Are you sure it works? – Gaurav May 19 '16 at 06:55
  • Depends on what the OP really wants (which is not clear atm) – Jaap May 19 '16 at 07:13