Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert numbers to dates [duplicate]

Tags:

r

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.

like image 738
bwilliams18 Avatar asked Jan 09 '13 22:01

bwilliams18


2 Answers

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

> as.Date(as.character(20130107), "%Y%m%d")
[1] "07-01-2013"
like image 106
Joshua Ulrich Avatar answered Sep 25 '22 15:09

Joshua Ulrich


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")
like image 23
ZeroStack Avatar answered Sep 23 '22 15:09

ZeroStack