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:
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).
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"
When dealing with dates, I find lubridate
can be very helpful:
library(lubridate)
mydata[, 1] <- mdy_hm(mydata[, 1])
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")