dplyr if_else() vs base R ifelse()

前端 未结 4 1144
野趣味
野趣味 2020-11-30 10:22

I am fairly proficient within the Tidyverse, but have always used ifelse() instead of dplyr if_else(). I want to switch this behavior and default t

4条回答
  •  隐瞒了意图╮
    2020-11-30 10:56

    if_else is more strict. It checks that both alternatives are of the same type and otherwise throws an error, while ifelse will promote types as necessary. This may be a benefit in some circumstances, but may otherwise break scripts if you don't check for errors or explicitly force type conversion. For example:

    ifelse(c(TRUE,TRUE,FALSE),"a",3)
    [1] "a" "a" "3"
    if_else(c(TRUE,TRUE,FALSE),"a",3)
    Error: `false` must be type character, not double
    

提交回复
热议问题