Error creating R data.table with date-time POSIXlt

前端 未结 1 1886
猫巷女王i
猫巷女王i 2020-12-03 10:19

Problem creating data.table with date-time column:

> mdt <- data.table(id=1:3, d=strptime(c(\"06:02:36\", \"06:02:48\", \"07:03:12\"), \"%H:%M:%S\"))
&         


        
相关标签:
1条回答
  • 2020-12-03 11:09

    Formatting response from Blue Magister's comment (thanks so much), data.table does not support POSIXlt data types for performance reason -- see cast string to IDateTime as suggested as possible duplicate.

    So the way to go is to cast time as ITime (type provided by data.table) or date-time (or date only) as POSIXct, depending upon whether date info is important or not:

    > mdt <- data.table(id=1:3, d=as.ITime(strptime(c("06:02:36", "06:02:48", "07:03:12"), "%H:%M:%S")))
    > print(mdt)
       id        d
    1:  1 06:02:36
    2:  2 06:02:48
    3:  3 07:03:12
    > mdt <- data.table(id=1:3, d=as.POSIXct(strptime(c("06:02:36", "06:02:48", "07:03:12"), "%H:%M:%S")))
    > print(mdt)
       id                   d
    1:  1 2014-01-31 06:02:36
    2:  2 2014-01-31 06:02:48
    3:  3 2014-01-31 07:03:12
    

    As an extra note in case someone can benefit from it, I wanted to create date & time from my input data with date & time in separate fields. I found it useful to learn (see ?ITime) that one can add time ITime to date-time POSIXct and get a date-time POSIXct as follows:

    > mdt <- as.POSIXct("2014-01-31") + as.ITime("06:02:36")
    > print(mdt)
    [1] "2014-01-31 06:02:36 EST"
    > class(mdt)
    [1] "POSIXct" "POSIXt" 
    
    0 讨论(0)
提交回复
热议问题