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 need 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 line of df1.
Is there a way to get the desired result using plyr (mdplyr ??) or dplyr?
I see no reason for "dplyr" for anything like that. In the R database, you can simply do:
df1 + unclass(df2) # a b # 1 14 28 # 2 15 29 # 3 16 30 # 4 17 31 # 5 18 32 # 6 19 33
Same as df1 + list(4, 8).
df1 + list(4, 8)
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
Basic solution Rusing a sweet function sweep:
R
sweep
sweep(df1, 2, unlist(df2), '+') # a b #1 14 28 #2 15 29 #3 16 30 #4 17 31 #5 18 32 #6 19 33