问题
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.
回答1:
Lubridate does this for you:
library(lubridate)
dmy(01102013)
回答2:
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"
回答3:
@JoshuaUlrich's answer is good, but to answer your other question ("how do I insert separators between the parts of the date?") ... (you still need make sure you do the zero-padding when converting from numeric to character, as Josh shows)
cdate <- sprintf("%08d",date)
datestr <- paste(substr(cdate,1,2),
substr(cdate,3,4),substr(cdate,5,8),sep="/")
as.Date(datestr,format="%d/%m/%Y")
来源:https://stackoverflow.com/questions/21117112/turning-an-integer-string-date-into-an-actual-date