1

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.

user438383
  • 5,716
  • 8
  • 28
  • 43
cory
  • 49
  • 4
  • 1
    `data %>% mutate(x = if_else(x < 0, NA_real_, x))`. NA_real_ is the equivalent for numeric NA. `dplyr::if_else` is specifically written to force you to have the same type in your `true` and `false` arguments. – TarJae Aug 31 '22 at 20:59
  • 1
    Note that this same issue will also happen if you use vectorized versions of `dplyr::if_else()` such as `dplyr::case_when()` which lets you do multiple `if_else()` statements https://stackoverflow.com/questions/44893933/avoiding-type-conflicts-with-dplyrcase-when – socialscientist Aug 31 '22 at 21:03

1 Answers1

2

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
socialscientist
  • 3,759
  • 5
  • 23
  • 58