Join column from one dataset with another dataset

I would like to create a new dataset called df3 that joins the two datasets and looks like this:

Output

   date2   coef
01-01-2022   1
01-01-2022   2
03-01-2021   3
03-01-2021   2
01-02-2021   4
01-02-2021   5

That is, it is selected in the first column of df1 with the datbase df2

df1<- structure(
        list(date2= c("01-01-2022","01-01-2022","03-01-2021","03-01-2021","01-02-2021","01-02-2021"),
             Category= c("ABC","CDE","ABC","CDE","ABC","CDE"),
             coef= c(5,4,0,2,4,5)),
        class = "data.frame", row.names = c(NA, -6L))
      
      
             date2 Category coef
1 01-01-2022      ABC    5
2 01-01-2022      CDE    4
3 03-01-2021      ABC    0
4 03-01-2021      CDE    2
5 01-02-2021      ABC    4
6 01-02-2021      CDE    5

  df2<- structure(
        list(coef= c(1,2,3,2,4,5)),
        class = "data.frame", row.names = c(NA, -6L))

  coef
1    1
2    2
3    3
4    2
5    4
6    5
df1 <- data.frame(
    date2 = c("01-01-2022", "01-01-2022", "03-01-2021", "03-01-2021", "01-02-2021", "01-02-2021"),
    Category = c("ABC", "CDE", "ABC", "CDE", "ABC", "CDE"),
    coef = c(5, 4, 0, 2, 4, 5))


df2 <- data.frame(coef = c(1, 2, 3, 2, 4, 5))

# A join does not produce what was given as the desired output
dplyr::inner_join(df1,df2,by="coef")
#>        date2 Category coef
#> 1 01-01-2022      ABC    5
#> 2 01-01-2022      CDE    4
#> 3 03-01-2021      CDE    2
#> 4 03-01-2021      CDE    2
#> 5 01-02-2021      ABC    4
#> 6 01-02-2021      CDE    5

# use this, instead
data.frame(date2 = df1$date2, coef = df2$coef)
#>        date2 coef
#> 1 01-01-2022    1
#> 2 01-01-2022    2
#> 3 03-01-2021    3
#> 4 03-01-2021    2
#> 5 01-02-2021    4
#> 6 01-02-2021    5
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.