Runner Bean
Runner Bean

Reputation: 5155

merge data frames: assign values to multiple rows

I'm new to R and trying to merge two data frames df1 and df2.

df1 looks like

    user_id     A     B
1      112      1     1
2      113      0     4
3      114      7     2

df2 looks like

     user_id     date           C
1     112       2016-04-01      6
2     112       2016-04-02      9    
3     112       2016-04-03      1
4     113       2016-04-01      13
5     113       2016-04-02      4
6     113       2016-04-03      9
7     114       2016-04-01      3
8     114       2016-04-02      7
9     114       2016-04-03      8

and I want to merge these two by 'user_id' assigning the values of df1 to all the corresponding user_id rows of df2. To make

     user_id     date           A    B    C
1     112       2016-04-01      1    1    6
2     112       2016-04-02      1    1    9    
3     112       2016-04-03      1    1    1
4     113       2016-04-01      0    4    13
5     113       2016-04-02      0    4    4
6     113       2016-04-03      0    4    9
7     114       2016-04-01      7    2    3
8     114       2016-04-02      7    2    7
9     114       2016-04-03      7    2    8

how can this be coded?

Upvotes: 0

Views: 189

Answers (1)

nurandi
nurandi

Reputation: 1618

As simple as

merge(df1, df2)

Or, if you want to return all rows from df2

merge(df1, df2, all.y = TRUE)

See this for details

Upvotes: 1

Related Questions