match - Conditional merge/replacement in R -


i have 2 data frames:

df1 x1  x2 1   2   b 3   c 4   d 

and

df2 x1  x2 2   zz 3   qq 

i want replace of values in df1$x2 values in df2$x2 based on conditional match between df1$x1 , df2$x2 produce:

df1 x1  x2 1   2   zz 3   qq 4   d 

use match(), assuming values in df1 unique.

df1 <- data.frame(x1=1:4,x2=letters[1:4],stringsasfactors=false) df2 <- data.frame(x1=2:3,x2=c("zz","qq"),stringsasfactors=false)  df1$x2[match(df2$x1,df1$x1)] <- df2$x2 > df1   x1 x2 1  1  2  2 zz 3  3 qq 4  4  d 

if values aren't unique, use :

for(id in 1:nrow(df2)){   df1$x2[df1$x1 %in% df2$x1[id]] <- df2$x2[id] } 

Comments

Popular posts from this blog

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -

python - Error while using APScheduler: 'NoneType' object has no attribute 'now' -