R-if_else分配na值

Skl*_*cka 2 if-statement r

我在R中有一个数据框。我的目标是创建一个带if_else语句的新列。如果一行中的值等于string "company",则此新列的值将是data列中的值。否则,我想分配给if NA值。

我不知道如何实现,下面的代码不起作用。由于数据类型不同。

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
Run Code Online (Sandbox Code Playgroud)

tho*_*hal 7

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"
Run Code Online (Sandbox Code Playgroud)

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_

  • 谢谢你@thothal。我一直在几个争论中与 NA 作斗争......不知道你可以为其分配一个类型。 (2认同)

NCo*_*oll 7

dplyr::case_when或许也可以在这里使用

library(dplyr)
  active_labels <- data %>%
      mutate(start_date = case_when(type == "company" ~ date, 
                                    TRUE ~ NA) 
Run Code Online (Sandbox Code Playgroud)