简体   繁体   中英

R dplyr: adding set of columns to other set of columns using dplyr

I have two simple dataframes (dfOne and dfTwo), for which I want to add a selection of columns of the second dataframe (selectedColumnsTwo) to a selection of columns of the first (selectedColumnsOne):

dfOne <- data.frame(list("a1"=c(1,2,3), "b1"=c(4,5,6), "c1"=c(7,8,9)))
dfTwo <- data.frame(list("a2"=c(1,2,3), "b2"=c(4,5,6)))
selectedColumnsOne = c("a1", "b1")
selectedColumnsTwo = c("a2", "b2")

Where the dataframes look like:

> dfOne
  a1 b1 c1
1  1  4  7
2  2  5  8
3  3  6  9

> dfTwo
  a2 b2
1  1  4
2  2  5
3  3  6

I know this can be very easily done with some base R:

dfOne[selectedColumnsOne] = dfOne[,selectedColumnsOne]+dfTwo[,selectedColumnsTwo ]

Giving the desired result:

> dfOne
  a1 b1 c1
1  2  8  7
2  4 10  8
3  6 12  9

However, I'm using dplyr for all my dataframe modifications, and it would benefit the readability if I did this with dplyr instead of base R. So, is there also a way to do it with dplyr?

EDIT

This is just an example. My original two dataframes is much larger, and I would like a solution which does not bind the two dataframes. Also, I am looking for a solution which uses the variables selectedColumnsOne and selectedColumnsTwo, and which doesn't need to refer to the the other columns (column "c1" in the example)

Also, Im using dplyr 0.7.2, and it would be preferable if the solution works in this version

I was looking at something like mutate_at, but that doesn't work:

> dfOne <- dfOne %>% mutate_at(selectedColumnsOne, .funs=funs(.+dfTwo[,selectedColumnsTwo ]))

Error in mutate_impl(.data, dots) : 
  Column `a1` must be length 3 (the number of rows) or one, not 2

One option could be:

bind_cols(dfOne, dfTwo) %>%
 transmute(across(a1:b1) + across(a2:b2),
           c1)

  a1 b1 c1
1  2  8  7
2  4 10  8
3  6 12  9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM