将日期转换为因子以进行顺序分析

时间:2019-03-08 14:36:40

标签: r date sequential factors event-id

我想将Date转换为因子以进行顺序分析。 repdate should be converted into factor for further analysis

我尝试了以下代码:

start_month <- '2019-01-01'



elapsed_month <- function(end_date, start_date) {
ed <- as.POSIXlt(end_date)
sd <- as.POSIXlt(start_date)
12 * (ed$year - sd$year) + (ed$mon - sd$mon)
}

trans_sequence$eventID <- elapsed_month(trans_sequence$repdate, 
start_month)

但是我得到以下输出: eventID

我希望以下输出: enter image description here

谢谢您的帮助!

1 个答案:

答案 0 :(得分:1)

为什么不只使用:

as.Date(trans_sequence$repdate)-as.Date('2019-01-01')

示例:

cc<-as.Date(c("2019-01-02", "2019-01-03", "2019-01-04", "2019-01-05", "2019-01-06", "2019-01-07", "2019-01-08"))
cc
 [1] "2019-01-02" "2019-01-03" "2019-01-04" "2019-01-05"
 [5] "2019-01-06" "2019-01-07" "2019-01-08"
cc-as.Date('2019-01-01')
 Time differences in days
 [1] 1 2 3 4 5 6 7