Row-wise multiplication of selected columns with dplyr

Viewed 473

What is the way to perform row-wise multiplication of all columns selected from a daraframe. Below Mult columns is created explicitly by saying what variables to multiply.

What if I selected different columns? What code needs to be in mutate so it will multiply all columns selected before? NOTE: number of selected columns will not always be three.

example:

library(tidyverse)

mtcars %>% 
  select(hp, qsec, disp) %>% 
  mutate(mult = hp * qsec * disp)

2 Answers

One possible way would be using rowProds from package matrixStats:

mtcars %>% 
  select(hp, qsec, disp) %>% 
  mutate(mult=rowProds(as.matrix(.)))

But I am sure there is a more elegant way without using another package.

You can use Reduce -

library(dplyr)

mtcars %>% 
  select(hp, qsec, disp) %>% 
  mutate(mult = Reduce(`*`, .))

Or rowwise with prod -

mtcars %>% 
  select(hp, qsec, disp) %>% 
  rowwise() %>%
  mutate(mult = prod(c_across()))
Related