dplyr if_else() vs base R ifelse()

前端 未结 4 1140
野趣味
野趣味 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:44

    Another reason to choose if_else over ifelse is that ifelse turns Date into numeric objects

    Dates <- as.Date(c('2018-10-01', '2018-10-02', '2018-10-03'))
    new_Dates <- ifelse(Dates == '2018-10-02', Dates + 1, Dates)
    str(new_Dates)
    
    #>  num [1:3] 17805 17807 17807
    

    if_else is also faster than ifelse.

    Note that when testing multiple conditions, the code would be more readable and less error-prone if we use case_when.

    library(dplyr)
    
    case_when(
      Dates == '2018-10-01' ~ Dates - 1,
      Dates == '2018-10-02' ~ Dates + 1,
      Dates == '2018-10-03' ~ Dates + 2,
      TRUE ~ Dates
    )
    
    #> [1] "2018-09-30" "2018-10-03" "2018-10-05"
    

    Created on 2018-06-01 by the reprex package (v0.2.0).

提交回复
热议问题