[R] Adding a year to existing date

Petr PIKAL petr.pikal at precheza.cz
Fri Nov 18 08:45:34 CET 2011


Hi

> 
> On 17/11/11 17:33, arunkumar1111 wrote:
> > Hi
> >
> >   I need to add an year to and date field in the dataframe.
> >
> > Please help me
> >
> > X Date
> > 1 2008-01-01
> > 2 2008-02-01
> > 3 2003-03-01
> 
> I can't find anything built in.  This is probably because "year" is an 
> ill-defined
> unit; years vary in length in a somewhat peculiar fashion.  So doing 
> arithmetic
> with respect to years is frowned on.
> 
> However you might try this:
> 
> `%+%` <- function(x,y){
> if(!isTRUE(all.equal(y,round(y)))) stop("Argument \"y\" must be an 
> integer.\n")
>   x <- as.POSIXlt(x)
>   x$year <- x$year+y
> as.Date(x)
> }
> 
> Then:
> 
> xxx <- as.Date(c("2008-01-01","2008-02-01","2003-03-01"))
> xxx %+% 1
> [1] "2009-01-01" "2009-02-01" "2004-03-01"

another option is

paste((as.numeric(format(xxx, "%Y"))+1), format(xxx,"%m-%d"), sep="-")

Regards
Petr


> 
> Dunno what dangers lurk; caveat utilitor.
> 
>      cheers,
> 
>          Rolf Turner
> 
> ______________________________________________
> 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.



More information about the R-help mailing list