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
  • 27,303
  • 19
  • 84
  • 117
Gabriele Midolo
  • 231
  • 1
  • 9

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
  • 874,273
  • 37
  • 540
  • 662