Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a factor into date format?

Tags:

r

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.)

like image 649
Ben Avatar asked Jul 05 '13 20:07

Ben


People also ask

How do I change a factor to a date in R?

Convert Factor to Date Using the ymd() function in R The ymd() function is available in the lubridate library, which transforms the given factor dates into Date or POSIXct objects in the %Y-%m-%d format.

How do you convert a factor?

Converting a Factor that is a Number: If the factor is number, first convert it to a character vector and then to numeric. If a factor is a character then you need not convert it to a character. And if you try converting an alphabet character to numeric it will return NA.

How do I convert a char to a date in R?

You can use the as. Date( ) function to convert character data to dates. The format is as. Date(x, "format"), where x is the character data and format gives the appropriate format.

How do I convert a whole column to a date?

Convert text dates by using the DATEVALUE function Select a blank cell and verify that its number format is General. Click the cell that contains the text-formatted date that you want to convert. Press ENTER, and the DATEVALUE function returns the serial number of the date that is represented by the text date.


2 Answers

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" 
like image 169
G. Grothendieck Avatar answered Sep 19 '22 22:09

G. Grothendieck


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)) 
like image 22
Jd Baba Avatar answered Sep 18 '22 22:09

Jd Baba