【问题标题】:Convert Date into Factors for sequential analysis将日期转换为因子以进行顺序分析
【发布时间】:2019-03-08 14:36:39
【问题描述】:

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

我尝试了以下代码:

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)

但我得到以下输出:

我希望得到以下输出:

感谢您的帮助!!

【问题讨论】:

  • 你能用dputdput(head(trans_sequence$repdate))显示tran_sequence$repdate吗
  • 结构(c(47L, 56L, 29L, 59L, 66L, 46L), .Label = c("2019-01-02", "2019-01-03", "2019-01 -04”、“2019-01-05”、“2019-01-06”、“2019-01-07”、“2019-01-08”、“2019-01-09”、“2019-01-10” ", "2019-01-11", "2019-01-12", "2019-01-13", "2019-01-14", "2019-01-15", "2019-01-16", “2019-01-17”等......
  • 请根据this编辑您的问题,以帮助未来的观众(您也是)。

标签: r date sequential factors event-id


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多