'Modifying Values in Two Different Data Frames with Different Lengths - R

I have two columns that essentially look like this:

DF1

ID Time Value New
1 0 82 NA
2 0 66 NA
3 0 74 NA
1 1 62 NA
2 1 78 NA
1 2 73 NA

DF2

Avg Time
76 0
83 1
70 2
71 3
77 4

I want to either add the averages in DF2 to the "New" column in DF1 grouped by Time (i.e. each ID with Time "0" would all have 76 in the "new" column, every ID with Time 1 would have 83, and so on), so that I may subtract them individually in one data frame...

OR

I would like to directly subtract each value in DF1 by its corresponding avg in DF2 based on its Time category.

Thank you for any help.

r


Solution 1:[1]

We could use left_join

library(dplyr)
left_join(df1, df2, by = "Time")
  ID Time Value New Avg
1  1    0    82  NA  76
2  2    0    66  NA  76
3  3    0    74  NA  76
4  1    1    62  NA  83
5  2    1    78  NA  83
6  1    2    73  NA  70

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TarJae