Search code examples
rmergeleft-join

join df1 and df2 by row index


I have two data frames, data frame 1:

df1 <- data.frame(ID = c('a', 'b', 'c', 'c1', 'd', 'e', 'f', 'g', 'h', 'h1'),
                 var2 = c(7, 9, 2, 4, 3, 6, 8, 2, 1, 2),
                 var3 = c(21, 50, 40, 30, 29, 45, 33, 51, 70, 46),
                 df2_id = c(1, 5, 2, 4, 1, 2, 3, 3, 5, 1))

And data frame 2:

df2 <- data.frame(pcd = c('e1', 'm35', 'sk3', 'bk4', 'nw2'),
                 x = c(6, 8, 2, 1, 2),
                 y = c(5, 3, 1, 7, 6))

I want to "left_join" df2 to df1, based on the row index reported in df1$df2_id, so that the output looks like this:

> df1
   ID var2 var3 df2_id pcd x y
1   a    7   21      1  e1 6 5
2   b    9   50      5 nw2 2 6
3   c    2   40      2 m35 8 3
4  c1    4   30      4 bk4 1 7
5   d    3   29      1  e1 6 5
6   e    6   45      2 m35 8 3
7   f    8   33      3 sk3 2 1
8   g    2   51      3 sk3 2 1
9   h    1   70      5 nw2 2 6
10 h1    2   46      1  e1 6 5

Solution

  • Using :

    left_join(df1, rowid_to_column(df2, "df2_id"))