Convert Factor to Date/Time in R

前端 未结 2 354
遥遥无期
遥遥无期 2020-12-01 15:04

This is the information contained within my dataframe:

## minuteofday: factor w/ 89501 levels \"2013-06-01 08:07:00\",...
## dDdt: num 7.8564 2.318 ...
## mi         


        
相关标签:
2条回答
  • 2020-12-01 15:17

    You need to insert an as.character() before parsing as a Datetime or Date.

    A factor will always come back first as a number corresponding to its level.

    You can save the conversion from factor to character by telling read.csv() etc to no store as a factor: stringsAsFactors=FALSE. You can also set that as a global option.

    Once you have it as character, make sure you match the format string to your data:

    R> as.POSIXct("2013-06-01 08:07:00", format="%Y-%m-%d %H:%M:%S")
    [1] "2013-06-01 08:07:00 CDT"
    R> 
    

    Note the %Y-%m-%d I used, as opposed to your %m/%d/%y.

    Edit on 3 Jan 2016: This is now much easier thanks to the anytime package which automagically converts from many types, including factor, and does so without requiring a format string.

    R> as.factor("2013-06-01 08:07:00")
    [1] 2013-06-01 08:07:00
    Levels: 2013-06-01 08:07:00
    R> 
    R> library(anytime)
    R> anytime(as.factor("2013-06-01 08:07:00"))
    [1] "2013-06-01 08:07:00 CDT"
    R> 
    R> class(anytime(as.factor("2013-06-01 08:07:00")))
    [1] "POSIXct" "POSIXt" 
    R> 
    

    As you can see we just feed the factor variable into anytime() and out comes the desired POSIXct type.

    0 讨论(0)
  • 2020-12-01 15:31

    Try this

    library(lubridate) minuteave$minutes <- ymd_hms(minuteave$minutes)

    this will return minuteave$minutes as a POSIXct object.

    Hope this helps you.

    0 讨论(0)
提交回复
热议问题