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
.
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 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:
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.
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.
you can use NA_real_
if_else(mtcars$cyl > 5, NA_real_, 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With