'R - if_else assign na value
I have a dataframe in R. My goal is to create a new column with if_else
statement. If the value in a row is equal to the string "company"
, then the value of this new column will be the value from data column. Otherwise, I'd like to assign to if NA
value.
I don't know how to achieve that, my code below does not work. Because of a different data type.
library(dplyr)
active_labels <- data %>%
mutate(start_date = if_else(type == "company", date, NA)
Error in mutate_impl(.data, dots) :
Evaluation error: `false` must be type double, not logica
Solution 1:[1]
From the help page of if_else
:
Compared to the base ‘ifelse()’, this function is more strict. It checks that ‘true’ and ‘false’ are the same type.
That means that date
and NA
must be of the same type. As it happens, NA
has also a type and it is logical
:
typeof(NA)
# [1] "logical"
Thus, you need a typed version of NA
. Depending on which type date
is you should use either:
NA_real_ : typeof(NA_real_) # [1] "double"
NA_integer_ : typeof(NA_integer_) # [1] "integer"
NA_character_: typeof(NA_character_) # [1] "character"
NA_complex_ : typeof(NA_complex_) # [1] "complex"
If date
is none of the above, you should fall back to ifelse
.
Edit: from the error message you got, you should most probably use NA_real_
Solution 2:[2]
Might be able to use dplyr::case_when
here as well
library(dplyr)
active_labels <- data %>%
mutate(start_date = case_when(type == "company" ~ date,
TRUE ~ NA)
Solution 3:[3]
Try to use na_if()
, this works with Dates.
library(dplyr)
active_labels <- data %>%
mutate(start_date = date,
start_date = na_if(type, "company"))
Solution 4:[4]
Try this:
active_labels <- data
active_labels$start_date <- ifelse (active_labels$type == "company", active_labels$date, NA)
Hope it helps.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | NColl |
Solution 3 | Laszlo |
Solution 4 |