R - Help in Converting Factor to Date (%M/%D/%Y %H:%M)

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

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"

Parse m/%d/%Y %H:%M form of datetime in R

You just forgot a % in the beginning of your format string, this should work:

strptime(df$time, format="%m/%d/%Y %H:%M")

How do I convert a factor into date format?

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"

Convert Factor to Date/Time in R

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.

Convert string to date, format: dd.mm.yyyy

The format is case-sensitive ("%y" is ambiguous and system dependent, I believe):

as.Date(D, "%d.%m.%Y")
[1] "1948-12-06"

The help topic ?strptime has details:

 ‘%y’ Year without century (00-99).  On input, values 00 to 68 are
prefixed by 20 and 69 to 99 by 19 - that is the behaviour
specified by the 2004 and 2008 POSIX standards, but they do
also say ‘it is expected that in a future version the default
century inferred from a 2-digit year will change’.


Related Topics



Leave a reply



Submit