Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional merge/replacement in R

Tags:

r

r-faq

match

I have two data frames:

df1 x1  x2 1   a 2   b 3   c 4   d 

and

df2 x1  x2 2   zz 3   qq 

I want to replace some of the values in df1$x2 with values in df2$x2 based on the conditional match between df1$x1 and df2$x2 to produce:

df1 x1  x2 1   a 2   zz 3   qq 4   d 
like image 831
Mike Avatar asked May 24 '11 14:05

Mike


People also ask

How do you left join in R?

To perform left join use either merge() function, dplyr left_join() function, or use reduce() from tidyverse. Using the dplyr function is the best approach as it runs faster than the R base approach. dplyr package provides several functions to join data frames in R.


1 Answers

use match(), assuming values in df1 are 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  a 2  2 zz 3  3 qq 4  4  d 

If the values aren't unique, use :

for(id in 1:nrow(df2)){   df1$x2[df1$x1 %in% df2$x1[id]] <- df2$x2[id] } 
like image 113
Joris Meys Avatar answered Sep 28 '22 00:09

Joris Meys