Search code examples
rdplyrdata-cleaningdata-wrangling

Add corresponding columns of data frame in R


Here's the example data I have.

df1 <- tibble(a=1:4,
              b=1:4,
              c=1:4,
              d=1:4,
              e=1:4)

# A tibble: 4 x 5
      a     b     c     d     e
  <int> <int> <int> <int> <int>
1     1     1     1     1     1
2     2     2     2     2     2
3     3     3     3     3     3
4     4     4     4     4     4
df2 <- tibble(b=1:4,
              d=1:4,
              e=1:4)

      b     d     e
  <int> <int> <int>
1     1     1     1
2     2     2     2
3     3     3     3
4     4     4     4

I would like to add the columns in common so that I can get a data frame like this

      a     b     c     d     e
  <int> <dbl> <int> <dbl> <dbl>
1     1     2     1     2     2
2     2     4     2     4     4
3     3     6     3     6     6
4     4     8     4     8     8

Is there an easy way to do this in R with tools like dplyr?


Solution

  • An easier option is to subset the first dataset 'df1' based on the column names of 'df2' (assuming all the columns in 'df2' are present in 'df1'), add those and assign back to the those in 'df1'

    df1[names(df2)] <- df1[names(df2)] + df2
    

    Or using dplyr

    library(dplyr)
    df1 %>% 
        mutate(c_across(names(df2)) + df2)
    

    -output

    # A tibble: 4 x 5
    #      a     b     c     d     e
    #  <int> <int> <int> <int> <int>
    #1     1     2     1     2     2
    #2     2     4     2     4     4
    #3     3     6     3     6     6
    #4     4     8     4     8     8