I would like to convert these dates with format YYYYMMDD to a Date class.
dates <- data.frame(Date = c("20130707", "20130706", "20130705", "20130704"))
I tried:
dates <- as.Date(dates, "%Y%m%d")
And I get the following error:
Error in as.Date.default(dates, "%Y%m%d") : do not know how to convert 'dates' to class "Date"
What would be the correct way to set this format?
Method 1: Using as.POSIXct() method A string type date object can be converted to POSIXct object, using them as. POSIXct(date) method in R. “ct” in POSIXct denotes calendar time, it stores the number of seconds since the origin. It takes as input the string date object and the format specifier.
To convert a data frame column of type string into date/time in R, call as. POSIXct() function and pass the column as argument to this function. We may optionally pass time zone, date/time format, etc., to this function. POSIXct class represents the calendar dates and times.
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.
You need to provide the Date
column, not the entire data.frame
.
R> as.Date(dates[["Date"]], "%Y%m%d") [1] "2013-07-07" "2013-07-06" "2013-07-05" "2013-07-04"
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