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

后端 未结 6 771
无人及你
无人及你 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条回答
  •  梦毁少年i
    2020-11-22 04:35

    The reason why this won't work is because, ifelse() function converts the values to factors. A nice workaround would be to convert it to characters before evaluating it.

    dates <- as.Date(c('2011-01-01','2011-01-02','2011-01-03','2011-01-04','2011-01-05'))
    dates_new <- dates - 1
    dates <- as.Date(ifelse(dates =='2011-01-01',as.character(dates_new),as.character(dates)))
    

    This wouldn't require any library apart from base R.

提交回复
热议问题