Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning an integer string date into an actual date

I'm trying to turn a date in the format of 01102013 (1st of October 2013), say, into an actual R date.

I found a similar question relating to C# but no solutions for R.

How to convert a date of integers to a formated date string (i.e. 2012009 to 2/01/2009)

I tried the obvious way of as.Date(date, format=%d%m%Y) but it came up with the error that the origin was missing (since it is reading the integer as a number of days since a date but it is the actual date just without dashes or slashes in between).

I also tried to find a way of inserting - or \ between the numbers to try and get R to recognise it but I can't find a way to do that either.

like image 942
Dr Vicki Avatar asked Dec 09 '22 10:12

Dr Vicki


2 Answers

Lubridate does this for you:

library(lubridate)
dmy(01102013)
like image 144
hadley Avatar answered Dec 10 '22 22:12

hadley


If you want to parse it as a character string, you need to convert it to character first. You also need to put quotes around the format string.

> date <- 01102013
> date
# [1] 1102013
# you need leading zeros, so you can't just use as.character()
> as.Date(sprintf("%08d", date), format="%d%m%Y")
# [1] "2013-10-01"
like image 44
Joshua Ulrich Avatar answered Dec 10 '22 23:12

Joshua Ulrich