Irakli
Irakli

Reputation: 1009

R: multiply all columns in a dataframe

My dataframe has all numeric columns (such as mtcars). How to create a new column that shows the product of all the columns? My attempt:

 library(tidyverse)
 mtcars %>% mutate(product=prod(mpg:carb))

yields incorrect product

    mpg  cyl  disp  hp  drat    wt   qsec  vs am  gear  carb      product
1  21.0   6 160.0  110  3.90  2.620  16.46  0  1    4    4      8.515157e+18
2  21.0   6 160.0  110  3.90  2.875  17.02  0  1    4    4      8.515157e+18
...

Upvotes: 3

Views: 4283

Answers (1)

akrun
akrun

Reputation: 887951

We can use Reduce

mtcars %>%
     mutate(Prod = Reduce(`*`, .))

Or use do

mtcars %>% 
    rowwise() %>%
    do(data.frame(., Prod = prod(unlist(.))))

Upvotes: 3

Related Questions