简体   繁体   中英

How do I convert a factor into date format?

I imported a CSV file with dates from a SQL query, but the dates are really date-time values and R doesn't seem to recognize them as dates:

> mydate
[1] 1/15/2006 0:00:00
2373 Levels: 1/1/2006 0:00:00 1/1/2007 0:00:00 1/1/2008 0:00:00 ... 9/9/2012 0:00:00
> class(mydate)
[1] "factor"
> as.Date(mydate)
Error in charToDate(x) : 
  character string is not in a standard unambiguous format

How do I convert mydate to date format? (I don't need to include the time portion.)

You were close. format= needs to be added to the as.Date call:

mydate <- factor("1/15/2006 0:00:00")
as.Date(mydate, format = "%m/%d/%Y")
## [1] "2006-01-15"

You can try lubridate package which makes life much easier

library(lubridate)

mdy_hms(mydate)

The above will change the date format to POSIXct

A sample working example:

> data <- "1/15/2006 01:15:00"
> library(lubridate)
> mydate <- mdy_hms(data)
> mydate
[1] "2006-01-15 01:15:00 UTC"
> class(mydate)
[1] "POSIXct" "POSIXt" 

For case with factor use as.character

data <- factor("1/15/2006 01:15:00")
library(lubridate)
mydate <- mdy_hms(as.character(data))

Take a look at the formats in ?strptime

R> foo <-  factor("1/15/2006 0:00:00")
R> foo <- as.Date(foo, format = "%m/%d/%Y %H:%M:%S")                                           
R> foo                                                                                       
 [1] "2006-01-15"                                                                             
R> class(foo)                                                                                
 [1] "Date"  

Note that this will work even if foo starts out as a character. It will also work if using other date formats ( as.POSIXlt , as.POSIXct ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM