[R] Replace any values in a data frame based on another data frame

Marine Regis marine.regis at hotmail.fr
Sun Jul 31 05:45:35 CEST 2016


Hello,

I have two data frames with different sizes but with the same number of columns.

> df1 <- data.frame(col1 = c(1:6), col2 = c(rep("a", 3), rep("b", 3)), col3 = c(rep("AA", 2), rep("BB", 2), rep("CC", 2)), col4=c(1,8,6,9,7,6))

> df1

  col1 col2 col3 col4

1    1    a   AA    1

2    2    a   AA    8

3    3    a   BB    6

4    4    b   BB    9

5    5    b   CC    7

6    6    b   CC    6



> df2< - data.frame(col1 = c(1,3,5,6), col2 = c(rep("a", 2), rep("b", 2)), col3 = c(rep("AA", 1), rep("EE", 1), rep("FF", 1), rep("CC", 1)), col4=c(1,8,5,9))



> df2

  col1 col2 col3 col4

1    1    a   AA    1

2    3    a   EE    8

3    5    b   FF    5

4    6    b   CC    9





Based on col1 and col2, how can I replace any values in col3 and col4 of df1 which don't match with those of df2 by the values of df2



In this example, the result will be:



> df1

   col1 col2 col3 col4

1    1    a   AA    1

2    2    a   AA    8

3    3    a   EE    8

4    4    b   BB    9

5    5    b   FF    5

6    6    b   CC    9



Thanks a lot for your help.

Have a nice day

Marine

	[[alternative HTML version deleted]]



More information about the R-help mailing list