In the if_else()
function in dplyr
, it requires that both the if:TRUE and if:FALSE elements are of the same class.
I wish to return NA
from my if_else()
statement.
But e.g.
if_else(mtcars$cyl > 5, NA, 1)
returns
Error:
false
has type 'double' not 'logical'
Because simply reading in NA
is logical, and 1 is numeric (double).
Wrapping as.numeric()
around the NA
works fine: e.g.
if_else(mtcars$cyl > 5, as.numeric(NA), 1)
returns
1 NA NA 1 NA NA NA NA 1 1 NA NA NA NA NA NA NA NA 1 1 1 1 NA NA NA NA 1 1 1 NA NA NA 1
As what I am hoping for.
But this feels kinda silly/unnecessary. Is there a better way of inputting NA
as a "numeric NA
" than wrapping it like this?
NB this only applies to the stricter dplyr::if_else
not base::ifelse
.
?"NA"
for a better understanding of what is going on with the NA. Also, check out the output ofifelse(mtcars$cyl > 5, "this", 1)
.