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.)
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.
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.
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.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With