Home > Net >  Match two dataframes and replace one's values with other column value in R
Match two dataframes and replace one's values with other column value in R

Time:12-29

I am trying to match two dataframes (df1 and df2) in r and based on the match, replace the values in df2 with another column value in df1.

 df1 <- data.frame(
  col1 = c("1,1", "1,2", "1,3", "2,1", "2,2", "2,3", "3,1", "3,2","3,3"),
  col2 = c("a", "b", "c", "d", "e", "f", "g", "h","I")
)

df2 <- data.frame(
  c("1,1",  "2,1",  "3,1"),
  c("1,2", ".", "3,2"),
  c("1,3", "2,3", "3,3")
)

I am trying to match df1's col1 with df2 and if there is a match, I need to replace df2 with df1's col2 value. If no match then leave df2 as it is.

The desired output should be:

df2 = 
a b c
d . f 
g h i

CodePudding user response:

Use a named vector constructed from 'df1' to match and replace the values in 'df2'. The values that are not matched will be NA (which can be replaced later if wanted)

df2[] <- with(df1, setNames(col2, col1))[as.matrix(df2)]
df2[is.na(df2)] <- ""
  •  Tags:  
  • r
  • Related