Home > other >  How to recode only some values in R to NA using dplyr::if_else?
How to recode only some values in R to NA using dplyr::if_else?

Time:09-01

I want to recode values below 0 to NA with dpylr::if_else, leaving all other values unchanged. I know there are other ways to do this, but I can't figure out why this doesn't work: data %>% mutate(x = if_else(x < 0, NA, x)) R returns this:

"false must be a logical vector, not a double vector."

I wish for false to remain the original values.

CodePudding user response:

The issue is that the NA is not the same type as the x in the FALSE condition. You can fix this by using NA_real_ instead.

library(dplyr)

dat <- data.frame(x = c(-1,0,1))

# Use NA_real_
dat %>% mutate(z = if_else(x < 0, NA_real_, x))
#>    x  z
#> 1 -1 NA
#> 2  0  0
#> 3  1  1
  • Related