Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert yyyymmdd string to Date class in R

Tags:

date

class

r

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?

like image 269
rwn1v Avatar asked Jul 08 '13 02:07

rwn1v


People also ask

How do I convert a column to a date in a Dataframe in R?

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.

How do I convert a data frame to a date in R?

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.

How do I convert a character 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.


1 Answers

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" 
like image 92
GSee Avatar answered Oct 02 '22 16:10

GSee