How to prevent ifelse() from turning Date objects into numeric objects

后端 未结 6 767
无人及你
无人及你 2020-11-22 04:04

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

6条回答
  •  既然无缘
    2020-11-22 04:26

    DWin's explanation is spot on. I fiddled and fought with this for a while before I realized I could simply force the class after the ifelse statement:

    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)
    class(dates)<- "Date"
    str(dates)
    

    At first this felt a little "hackish" to me. But now I just think of it as a small price to pay for the performance returns that I get from ifelse(). Plus it's still a lot more concise than a loop.

提交回复
热议问题