6

I have a table, one of the columns is dates in form at 20130109 or YearMonthDay with no spacing.

I'm trying to graph these points, and because of this odd spacing, end up with big gaps in the graph, and thus want to convert these numbers into dates.

I've been trying to use as.Date(as.character(20130107), "%y%m%d") but that always returns an NA.

zx8754
  • 52,746
  • 12
  • 114
  • 209
bwilliams18
  • 359
  • 2
  • 3
  • 9

2 Answers2

19

You need %Y (4 digit year) not %y (2 digit year):

> as.Date(as.character(20130107), "%Y%m%d")
[1] "07-01-2013"
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
3

Using lubridate

library(lubridate)

parse_date_time(as.character(20130107), "%Y%m%d")

If you wanted to just extract certain elements of the date, this is easy with strftime. For example, just the year:

strftime(parse_date_time(as.character(20130107), "%Y%m%d"), "%Y")
ZeroStack
  • 1,049
  • 1
  • 13
  • 25