I am using the function ifelse() to manipulate a date vector. I expected the result to be of class Date, and was surprised to get a numeric>
You may use data.table::fifelse (data.table >= 1.12.3) or dplyr::if_else.
data.table::fifelseUnlike
ifelse,fifelsepreserves the type and class of the inputs.
library(data.table)
dates <- fifelse(dates == '2011-01-01', dates - 1, dates)
str(dates)
# Date[1:5], format: "2010-12-31" "2011-01-02" "2011-01-03" "2011-01-04" "2011-01-05"
dplyr::if_elseFrom dplyr 0.5.0 release notes:
[
if_else] have stricter semantics thatifelse(): thetrueandfalsearguments must be the same type. This gives a less surprising return type, and preserves S3 vectors like dates" .
library(dplyr)
dates <- if_else(dates == '2011-01-01', dates - 1, dates)
str(dates)
# Date[1:5], format: "2010-12-31" "2011-01-02" "2011-01-03" "2011-01-04" "2011-01-05"