R - Help in Converting factor to date (%m/%d/%Y %H:%M)

前端 未结 4 1134
南旧
南旧 2021-01-23 20:57

I am importing a data frame into R, but R is not recognizing the columns with the dates as being in dates format.

> mydata[1,1] [1] 1/1/2003 0:00 216332 Levels:

相关标签:
4条回答
  • 2021-01-23 21:23

    If you are using read.table, read.csv or similar functions to read in the data then you could look at this solution for a way to specify which columns will be dates and have them automatically converted as they are read in. This will do the conversion on the character strings without any conversion to factor (which may be part of your problem).

    0 讨论(0)
  • 2021-01-23 21:33

    The levels mean you have a factor. You need to convert to character with as.character():

     dt <- as.POSIXct(as.character(mydata[ ,1]) format = "%m/%d/%Y %H:%M")
    

    The first item with time = 0:00 will not show the time when printed but the others will. The error is occuring because the POSIXlt object is a list of 11 item lists. Generally it is better to use as.POSIXct than to use strptime because strptime returns a POSIXlt object and they are a bit of a mess to work with.:

    d <- factor("1/1/2003 0:01")
    as.POSIXct( as.character(d), format = "%m/%d/%Y %H:%M")
    [1] "2003-01-01 00:01:00 PST"
    
    0 讨论(0)
  • 2021-01-23 21:42

    When dealing with dates, I find lubridate can be very helpful:

    library(lubridate)
    mydata[, 1] <- mdy_hm(mydata[, 1])
    
    0 讨论(0)
  • 2021-01-23 21:50

    If you don't want to deal with Levels, try this:

    First convert your data into character:

    data<- as.character(mydata[1,1])

    Then give the date format you need, for example:

    date<- format(as.POSIXct(data, tz="EST"),"%Y-%m-%d %H")

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