0 votes
1 view
in R Programming by (7.8k points)

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 vector instead. Here is an example:

dates <- as.Date(c('2011-01-01', '2011-01-02', '2011-01-03', '2011-01-04', '2011-01-05'))

dates <- ifelse(dates == '2011-01-01', dates - 1, dates)


This is especially surprising because performing the operation across the entire vector returns a Date object.

dates <- as.Date(c('2011-01-01', '2011-01-02', '2011-01-03', '2011-01-04','2011-01-05'))

dates <- dates - 1


Should I be using some other function to operate on Date vectors? If so, what function? If not, how do I force ifelse to return a vector of the same type as the input?

The help page for ifelse indicates that this is a feature, not a bug, but I'm still struggling to find an explanation for what I found to be surprising behavior.

1 Answer

0 votes
by (25.3k points)

To prevent this conversion, you can use the if_else function from the dplyr package that compared to the base ifelse(), is more strict. It checks that true and false are the same type. This strictness makes the output type more predictable and makes it somewhat faster.

The basic syntax is given below:

if_else(condition, true, false, missing = NULL)



Logical vector

true, false

Values to use for TRUE and FALSE values of condition. They must be either the same length as condition or length 1. They must also be the same type: if_else() checks that they have the same type and same class. All other attributes are taken from true.


If not NULL, will be used to replace missing values.

In your case:


dates <- if_else(dates == '2011-01-01', dates - 1, dates)


 Date[1:5], format: "2010-12-31" "2010-12-31" "2011-01-02" "2011-01-03" "2011-01-04"

Welcome to Intellipaat Community. Get your technical queries answered by top developers !