Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k 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)

str(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

str(dates)

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

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)

Arguments

condition

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.

missing

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

In your case:

library(dplyr)

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

 str(dates)

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

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...