How to get pmax over multiple variables with dplyr?

Using do.call we can evaluate pmax without specifying the variables, i.e.

mtcars %>% 
  mutate(new = do.call(pmax, c(select(., c(1, 7)), na.rm = TRUE)))

#    mpg cyl  disp  hp drat    wt  qsec vs am gear carb   new
#1  21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4 21.00
#2  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4 21.00
#3  22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1 22.80
#4  21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1 21.40
#5  18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2 18.70
#6  18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1 20.22
#7  14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4 15.84
#...

We can use pmaxby converting column names to symbols and then evaluate (!!!)

library(dplyr)
mtcars %>%
     mutate(new = pmax(!!! rlang::syms(names(.)[c(1, 7)])))
#  mpg cyl  disp  hp drat    wt  qsec vs am gear carb   new
#1  21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4 21.00
#2  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4 21.00
#3  22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1 22.80
#4  21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1 21.40
#5  18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2 18.70
#6  18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1 20.22
#7  14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4 15.84

Or another option is reduce

library(purrr)
mtcars %>%
      mutate(new = reduce(select(., c(1, 7)), pmax))

Here is one option using purrr::pmap_dbl

library(dplyr)
mtcars %>% mutate(new = purrr::pmap_dbl(select(., c(1, 7)), pmax, na.rm=TRUE))

   mpg cyl  disp  hp drat    wt  qsec vs am gear carb   new
1  21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4 21.00
2  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4 21.00
3  22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1 22.80
4  21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1 21.40
5  18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2 18.70
6  18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1 20.22
7  14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4 15.84
...

Tags:

R

Dplyr