Reputation: 3335
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
.
Upvotes: 8
Views: 3649
Reputation: 1960
Or you can use if_else_
from the package hablar
. It is as rigid as if_else
from dplyr
about types, but allows for generic NA. See,
library(hablar)
if_else_(mtcars$cyl > 5, NA, 1)
Upvotes: 0