Skip to content
Prev 280136 / 398506 Next

sum with dates

If "adding x years to a date" means "increase the YYYY part of a date by 
x", then it should be easiest to manipulate the character representation 
of your date.

dates <- as.Date(c("2001-01-12","2001-02-12","2001-03-12"))

addYear <- function(d,addyears) {
     Y <- as.numeric(strftime(d, "%Y")) + addyears
     as.Date(paste(Y, strftime(d,"-%m-%d"), sep = ""))
}

## (There are leapyears with more than 365 days.)
dates + 365*15
addYear(dates,15)

That said, you cannot "go one year ahead" from February 29, unless you 
go ahead by 4, 8, 12, ... years (unless the new year is divisible by 100 
but not by 400). One possibility would be to leave such dates as Feb 28.

addYear <- function(d,addyears) {
     Y <- as.numeric(strftime(d, "%Y")) + addyears
     YisLeapyear <- Y%%400==0L | ((Y%%4==0L) & !(Y%%100==0L))
     mdpart <- strftime(d,"-%m-%d")
     mdpart <- ifelse(mdpart == "-02-29" & YisLeapyear,
                      mdpart, "-02-28")
     as.Date(paste(Y, mdpart, sep = ""))

}

dates <- as.Date(c("2001-01-12","2001-02-12","2001-03-12",
                    "1899-02-28","1896-02-29","2000-03-01"))
addYear(dates,4)
addYear(dates,5)
addYear(dates,8)



Regards,
Enrico



Am 13.12.2011 04:17, schrieb R. Michael Weylandt: