Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

Convert yyyymmdd string to Date class in R

Writer Sophia Terry

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?

5 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"
2

An extra conversion to characters works for me:

dates<-as.Date(as.character(dates),format="%Y%m%d")

Without the conversion the following error occurs:

dates<-as.Date(dates,format="%Y%m%d")
Error in as.Date.numeric(dates, format = "%Y%m%d") : 'origin' must be supplied

Different error but this might help, works for POSIXct too, paste date and hours, format %Y%m%d%H

Classic R:

> start_numeric <- as.Date('20170215', format = '%Y%m%d');
> start_numeric
[1] "2017-02-15"
> format(start_numeric, "%Y%m%d")
[1] "20170215"

Use the lubridate package for an easy conversion:

date_test <- data.frame(Date = c("20130707", "20130706", "20130705", "20130704"))
date_test$Date <- ymd(date_test$Date)
date_test Date
1 2013-07-07
2 2013-07-06
3 2013-07-05
4 2013-07-04

Instead of using brackets, you can use variable name:

dates <- data.frame(Date = c("20130707", "20130706", "20130705", "20130704"))
as.Date(dates$Date, "%Y%m%d")
[1] "2013-07-07" "2013-07-06" "2013-07-05" "2013-07-04"