Petr
Petr

Reputation: 1817

Row-wise multiplication of selected columns with dplyr

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)

Upvotes: 2

Views: 1229

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388982

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()))

Upvotes: 1

Dayne
Dayne

Reputation: 502

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.

Upvotes: 3

Related Questions