Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add data frames row wise with [d]plyr

Tags:

r

dplyr

plyr

I have two data frames

df1
#    a  b
# 1 10 20
# 2 11 21
# 3 12 22
# 4 13 23
# 5 14 24
# 6 15 25

df2
#   a b
# 1 4 8

I want the following output:

df3
#    a  b
# 1 14 28
# 2 15 29
# 3 16 30
# 4 17 31
# 5 18 32
# 6 19 33

i.e. add df2 to each row of df1.

Is there a way to get the desired output using plyr (mdplyr??) or dplyr?

like image 741
Benoit Casault Avatar asked Dec 10 '22 23:12

Benoit Casault


2 Answers

I see no reason for "dplyr" for something like this. In base R you could just do:

df1 + unclass(df2)
#    a  b
# 1 14 28
# 2 15 29
# 3 16 30
# 4 17 31
# 5 18 32
# 6 19 33

Which is the same as df1 + list(4, 8).

like image 146
A5C1D2H2I1M1N2O1R2T1 Avatar answered Feb 15 '23 03:02

A5C1D2H2I1M1N2O1R2T1


One liner with dplyr.

mutate_each(df1, funs(.+ df2$.), a:b)

#   a  b
#1 14 28
#2 15 29
#3 16 30
#4 17 31
#5 18 32
#6 19 33
like image 28
jazzurro Avatar answered Feb 15 '23 03:02

jazzurro