-4

Both fairly large For example :

Df1

Name name2  code2 code3
A    1      2     3
B    1      2     3
C    1      2     3

Df2

Name      lat           lon
A         5             6
C         1             2

I want to compare df1 with df2, If match add in the (lat lon) col to df1

Df1

Name name 2 code2 code3  lat    lon
A    1     2     3      5      6
B    1     2     3
C    1     2     3      1      2

I have tried

test <- merge(df1, df2, by = 'Name', all = TRUE) 

However it said that column names 'name' 'name1' are duplicated in the result. ( please assume that changing the column name is not an option )

I also tried a for loop

For( i in 1: nrow(df1)) {
      If ( df1$`Name`[I] %in% df2$Name) {
            Df1$lat[I] = df2$lat 
      }
}

However I do not know how to get the matched lat and lon to add to df1. Any help? Thanks

Plle02
  • 33
  • 6

1 Answers1

0

Try something like this:

merge(df1, df2, by.x = 'Name1',by.y = 'Name', all = TRUE)

where by.x is df1 in this case and by.y is df2. It helps you to merge by columns containing the same data but having different names. Good luck!

Milosz
  • 118
  • 8