Add a series of data frames with [d] 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 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?

+4
source share
3 answers

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

The same as df1 + list(4, 8).

+7
source

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
+4
source

Basic solution Rusing a sweet function 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
+2
source

Source: https://habr.com/ru/post/1584615/


All Articles