Scransom
Scransom

Reputation: 3335

Specify class of NA in R (for if_else, dplyr)

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

Answers (3)

davsjob
davsjob

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

Pelishka
Pelishka

Reputation: 111

try the base function

ifelse(mtcars$cyl > 5, NA, 1)

Upvotes: 3

myincas
myincas

Reputation: 1540

you can use NA_real_

if_else(mtcars$cyl > 5, NA_real_, 1)

Upvotes: 18

Related Questions