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
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).