Sklenicka
Sklenicka

Reputation: 655

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

Upvotes: 21

Views: 16755

Answers (4)

Laszlo
Laszlo

Reputation: 21

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

library(dplyr)
active_labels <- data %>%
  mutate(start_date = date,
         start_date = na_if(type, "company"))

Upvotes: 2

thothal
thothal

Reputation: 20329

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_

Upvotes: 31

NColl
NColl

Reputation: 757

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) 

Upvotes: 7

Taher A. Ghaleb
Taher A. Ghaleb

Reputation: 5240

Try this:

active_labels <- data
active_labels$start_date <- ifelse (active_labels$type == "company", active_labels$date, NA)

Hope it helps.

Upvotes: 0

Related Questions