0

I have 2 data frames.

Data1 is like this (with length of 50)

|Depth|Age|
|1|56|
|2|78|
|3|104|
|4|157|
|5|200|

Data 2 is like this (with lenght of 300)

|Age|Rate|
|1|15.2|
|2|15.4|
|3|15.6|
|4|16.4|
|5|17.8|
|..|..|
|300|19.1|

I want to create a new column Rate in Data1 based on Age, and the value of Rate is from Data2 with corresponding Age (same age in Data1 and Data2).

I want the output to be like this:

|Depth|Age|Rate|
|1|56|18.1|
|2|78|20.1|
|3|104|21.0|
|4|157|20.2|
|5|200|23.1|

I tried if else and it said cannot work because the data frame's length is different.

Is there any way to do this?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
monruw
  • 101
  • 3

1 Answers1

0

Found it using match:

data1$rate <- data2$rate[match(data1$age,data2$age)]

I found the solution here Add column to data frame based on values of another column in another row

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
monruw
  • 101
  • 3