Search code examples
rdataframedata-analysis

update data frame variable according to another table


I have two data frames Table 1 and Table 2 each one with two variables (V1, V2) What I want to do is to update the V2 for each row of Table 1 according to V2 of Table 2.

For example, in Table 1 there are two rows with V1==27 and their respectively values of V2 are 6 and 7. According to Table 2 every V1==27 should be 6.5 so I want to update every V1==27 from Table 1 and set its V2=6.5.

How can I accomplish that with R?

Table 1
  V1     V2
   1     1
   5     2
   18    3
   24    4
   25    5
   27    6
   27    7

Table 2
  V1     V2
   1     1.0
   5     20000.0
   18    3.0
   24    4.0
   25    5.0
   27    6.5

Resulting Table 3
  V1     V2
   1     1.0
   5     20000.0
   18    3.0
   24    4.0
   25    5.0
   27    6.5
   27    6.5

Solution

  • A couple approaches:

    transform(table1, V2 = table2$V2[match(V1, table2$V1)])
    

    or

    merge(table1["V1"], table2, all.x = TRUE)