[R] Convert day of year back into a date format.

Prof Brian Ripley ripley at stats.ox.ac.uk
Tue Mar 27 22:31:07 CEST 2012


On 27/03/2012 19:30, Justin Haynes wrote:
> There may very well be a better solution, but this works.
>
> format(strptime(dayofyear, format="%j"), format="%m-%d")

The answer depends on the year (think leap years), so I think you need

strptime(paste("2008", dayofyear), format="%Y %j")

Probably a better idea is

as.Date(dayofyear - 1, origin = "2008-01-01")

(as Jan 1 is day 1).

> On Tue, Mar 27, 2012 at 11:12 AM, Sam Albers<tonightsthenight at gmail.com>wrote:
>
>> Hello,
>>
>> I am having trouble figuring out how to convert a Day of Year integer
>> back into a Date format. For example I have the following:
>>
>> date<-
>> c('2008-01-01','2008-01-02','2008-01-03','2008-01-04','2008-01-05','2008-01-06','2008-01-07',
>>
>> '2008-01-08','2008-01-09','2008-01-10','2008-01-11','2008-01-12','2008-01-13','2008-01-14','2008-01-15',
>>
>> '2008-01-16','2008-01-17','2008-01-18','2008-01-19','2008-01-20','2008-01-21','2008-01-22','2008-01-23')
>>
>> ## this is then converted into a number corresponding to the day of
>> the year like so:
>>
>> dayofyear<- strptime(date, format="%Y-%m-%d")$yday + 1
>>
>> ## Now my question is how do I get back to a date format (obviously
>> omitting the year).
>> ## The end result is that I'd like to be able to have axis labels as
>> something like "Month-Day" or just "Month"
>> ## instead of just an integers which isn't always intuitive for people
>> but I can't seem to figure out how to tell R
>> ## to recognize an integer as a date.
>>
>> Any suggestions?
>>
>> Many thanks in advance!
>>
>> Sam
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.


-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list