Skip to content
Prev 156551 / 398506 Next

R: Adding 1 month to a dataframe column

It works great!
Thank you so much Gabor

Angelo Linardi

-----Messaggio originale-----
Da: Gabor Grothendieck [mailto:ggrothendieck at gmail.com] 
Inviato: gioved? 18 settembre 2008 21.16
A: LINARDI ANGELO
Cc: r-help at r-project.org
Oggetto: Re: [R] Adding 1 month to a dataframe column

Try this:

  # example data - Jan 31/00, Feb 29/00, Mar 31/00, ..., Dec 31/00
  d <- seq(as.Date("2000-02-01"), by = "month", length = 12) - 1
  d

  # find beginning of next month
  nextmon  <- function(d) as.Date(cut(as.Date(cut(d, "month")) + 32, "month"))

  # add number of days from start of current month to next month
  nextmon(d) + as.POSIXlt(d)$mday - 1

  # If all your dates are at month end and  you want the plus 1 month
  # to be at month end too then replace last line with:

  nextmon(nextmon(d)) - 1

The last one can be done even more easily with as.yearmon from zoo.
It converts the dates to a year plus 0 for jan, 1/12 for feb, etc. Also,
as.Date.yearmon(..., frac = 1) converts back from yearmon class to
Date class using end of month for the result so:

  library(zoo)
  as.Date(as.yearmon(d) + 1/12, frac = 1)
On Thu, Sep 18, 2008 at 12:24 PM, <ANGELO.LINARDI at bancaditalia.it> wrote:
** Le e-mail provenienti dalla Banca d'Italia sono trasmesse in buona fede e non 
comportano alcun vincolo ne' creano obblighi per la Banca stessa, salvo che cio' non 
sia espressamente previsto da un accordo scritto.
Questa e-mail e' confidenziale. Qualora l'avesse ricevuta per errore, La preghiamo di 
comunicarne via e-mail la ricezione al mittente e di distruggerne il contenuto. La 
informiamo inoltre che l'utilizzo non autorizzato del messaggio o dei suoi allegati 
potrebbe costituire reato. Grazie per la collaborazione.
-- E-mails from the Bank of Italy are sent in good faith but they are neither binding on 
the Bank nor to be understood as creating any obligation on its part except where 
provided for in a written agreement. This e-mail is confidential. If you have received it 
by mistake, please inform the sender by reply e-mail and delete it from your system. 
Please also note that the unauthorized disclosure or use of the message or any 
attachments could be an offence. Thank you for your cooperation. **