Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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.

like image 447
Scransom Avatar asked Aug 31 '17 06:08

Scransom


People also ask

How to use dplyr if_else function in R?

First, we need to install and load the dplyr package to R: Then, we also have to create an example vector, to which we can apply the if_else function: Our example vector contains seven numeric values ranging from -3 to +3.

How do I replace Na with zero in dplyr?

How to Replace NA with Zero in dplyr You can use the following syntax to replace all NA values with zero in a data frame using the dplyr package in R: #replace all NA values with zero df <- df %>% replace (is.na(.), 0) You can use the following syntax to replace NA values in a specific column of a data frame:

How do I replace a value with Na in R?

As you can see based on the previous R code and the output of the RStudio console, we replaced the value 5 of our vector with NA. We can also use the na_if command to replace certain values of a data frame or tibble with NA.

What is na_if in R?

Source: R/na_if.R This is a translation of the SQL command NULLIF. It is useful if you want to convert an annoying value to NA.


1 Answers

you can use NA_real_

if_else(mtcars$cyl > 5, NA_real_, 1)
like image 107
myincas Avatar answered Oct 19 '22 20:10

myincas