[R] Subtracting number of days from a date

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed May 26 18:41:22 CEST 2004


On Wed, 26 May 2004, Hoeven, Maarten van der wrote:

> suppose I have a date, say May 15 2004, and I want to now what date it
> is 23 days before that date. The way to calculate the new date should
> (...) take account of leap years :)
> 
> 
> In pseudocode:
> 
> olddate <- "May 15 2004"
> newdate <- olddate-23
> 
> I looked around in POSIXct etc..., maybe I overlooked?

olddate <- as.Date("May 15 2004", "%B %d %Y")
newdate <- olddate - 23
newdate
[1] "2004-04-22"
format(newdate, "%B %d %Y")
[1] "April 22 2004"

looks straightforward enough to me (and it knows about leap years).

-- 
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