简体   繁体   中英

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM