0

Suppose to have:

x<-c(1,2,3,1)
y<-c(2,NA,1,1)

I want to create the following:

z<-c(2,2,3,1)

namely select the larger value, excluding NA a priori and keep the same value if x and y are equal.

Is there a way to do this in dplyr?

pogibas
  • 25,773
  • 19
  • 74
  • 108
Gabriele Midolo
  • 221
  • 1
  • 8

1 Answers1

1

We can use pmax in dplyr

library(dplyr)
tibble(x, y) %>%
    transmute(xy = pmax(x, y, na.rm = TRUE)) %>% 
    pull(xy)
#[1] 2 2 3 1

Or another option is reduce

library(purrr)
list(x, y) %>%
     reduce(pmax, na.rm = TRUE)
#[1] 2 2 3 1
akrun
  • 789,025
  • 32
  • 460
  • 575