Search code examples
rdataframedplyrmatrix-multiplication

How do I multiply a range of columns together in R?


All I want to do is multiply my numeric columns together to create a new column.

The below example is a simplification in that I'll have far more numeric columns than 2, so can't just do df$C2 * df$C3.

Essentially if I have a table that looks like:

df <- data.frame(C1=c('A','B','C','D'),C2=c(1,2,3,4),C3=c(5,6,7,8))

   C1 C2 C3
1  A  1  5
2  B  2  6
3  C  3  7
4  D  4  8

I'd like to return C4 where:

   C1 C2 C3 C4
1  A  1  5  5
2  B  2  6  12
3  C  3  7  21
4  D  4  8  32

I'd like to do it in a more dynamic way than writing out each column as I have far more than 2 and they'll continue to change.

Any advice would be greatly appreciated please!


Solution

  • Use rowwise in combination with c_across.

    And the most important part probably is to specify the columns to select which can be done with different tidy select helpers. Here‘s one option, assuming that all your columns start with C followed by a number:

    df %>%
      rowwise() %>%
      mutate(C4 = prod(c_across(num_range('C', 2:3)))) %>%
      ungroup()
    
    # A tibble: 4 x 4
      C1       C2    C3    C4
      <chr> <dbl> <dbl> <dbl>
    1 A         1     5     5
    2 B         2     6    12
    3 C         3     7    21
    4 D         4     8    32