Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - if_else assign na value

Tags:

r

if-statement

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
like image 342
Sklenicka Avatar asked Dec 05 '18 16:12

Sklenicka


2 Answers

Try to use na_if(), this works with Dates.

library(dplyr)
active_labels <- data %>%
  mutate(start_date = date,
         start_date = na_if(type, "company"))
like image 196
Laszlo Avatar answered Sep 19 '22 12:09

Laszlo


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_

like image 41
thothal Avatar answered Sep 19 '22 12:09

thothal