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:
It depends how your dates are stored, but generally you can just add
365*15 to them. E.g.,

print(x<- Sys.Date())
print(x + 365*15)

So for you,

dataset$dates<- dataset$dates + 365*15

Michael

On Mon, Dec 12, 2011 at 9:39 PM, Ana<rrast...@gmail.com>  wrote:
How do I sum 15 years to my dataset?

original dataset
         dates        val
1    2001-01-12    1.2
2    2001-02-12    1.2
3    2001-03-12    1.2

result
         dates        val
1 2016-01-12 1.2
2    2016-02-12 1.2
3    2016-03-12 1.2

______________________________________________
R-help@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.

______________________________________________
R-help@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.


--
Enrico Schumann
Lucerne, Switzerland
http://nmof.net/

______________________________________________
R-help@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.

Reply via email to