Irakli Irakli - 1 month ago 6
R Question

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
...

Answer

We can use Reduce

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

Or use do

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