Home > Net >  Assigning values from one data set to another dataset based on year
Assigning values from one data set to another dataset based on year

Time:10-21

I am curious if anyone knows how to apply the Value.1s for each year of df1 to their corresponding years in df2. This will hopefully create two columns for "Value.1" and "Value.2" inside df2. Obviously, the real dataset is quite large and I would rather not do this the long way. I imagine the code will start with df2 %>% mutate(...), ifelse? case_when? I really appreciate any help!

df1 <- data.frame(Year = c(2000:2002),
                           Value.1 = c(0:2))
Year Value.1
1 2000     0
2 2001     1
3 2002     2


df2 <- data.frame(Year = c(2000,2000,2000,2001,2001,2001,2002,2002,2002),
                  Value.2 = c(1:9))
 Year Value.2
1 2000     1
2 2000     2
3 2000     3
4 2001     4
5 2001     5
6 2001     6
7 2002     7
8 2002     8
9 2002     9

CodePudding user response:

"Joins" are your friend when uniting dataframes. They're easy to understand. Try this:

df3 <- dplyr::left_join(df2, df1, by = "Year")

  Year Value.2 Value.1
1 2000       1       0
2 2000       2       0
3 2000       3       0
4 2001       4       1
5 2001       5       1
6 2001       6       1
7 2002       7       2
8 2002       8       2
9 2002       9       2

CodePudding user response:

You can do:

df2 <- df2 %>%
  mutate(
    Value.1 = recode(Year,
                     !!!setNames(unique(df1$Value.1),
                                 unique(df1$Year))))
> df2
  Year Value.2 Value.1
1 2000       1       0
2 2000       2       0
3 2000       3       0
4 2001       4       1
5 2001       5       1
6 2001       6       1
7 2002       7       2
8 2002       8       2
9 2002       9       2
  •  Tags:  
  • r
  • Related