2012-04-25 24 views
35

Tengo una fecha a la que me gustaría agregarle días para encontrar una fecha futura.R Agregar los días a una fecha

por ejemplo, ¿cómo puedo encontrar la fecha que es 45 días después del 1/1/2001?

Respuesta

53

Uso +

> as.Date("2001-01-01") + 45 
[1] "2001-02-15" 
9

Sólo tiene que utilizar

as.Date("2001-01-01") + 45 

de R base, o la funcionalidad de la fecha en uno de los muchos paquetes aportados. Mi paquete RcppBDT ajusta la funcionalidad de Boost Date_Time, incluidos elementos como 'fecha del tercer miércoles' en un mes determinado.

Editar: Y incitado por @Andrie, aquí es un poco más de RcppBDT (que es principalmente un caso de prueba para módulos RCPP, en realidad).

R> library(RcppBDT) 
Loading required package: Rcpp 
R> 
R> str(bdt) 
Reference class 'Rcpp_date' [package ".GlobalEnv"] with 0 fields 
and 42 methods, of which 31 are possibly relevant: 
    addDays, finalize, fromDate, getDate, getDay, getDayOfWeek, getDayOfYear, 
    getEndOfBizWeek, getEndOfMonth, getFirstDayOfWeekAfter, 
    getFirstDayOfWeekInMonth, getFirstOfNextMonth, getIMMDate, getJulian, 
    getLastDayOfWeekBefore, getLastDayOfWeekInMonth, getLocalClock, getModJulian, 
    getMonth, getNthDayOfWeek, getUTC, getWeekNumber, getYear, initialize, 
    setEndOfBizWeek, setEndOfMonth, setFirstOfNextMonth, setFromLocalClock, 
    setFromUTC, setIMMDate, subtractDays 
R> bdt$fromDate(as.Date("2001-01-01")) 
R> bdt$addDays(45) 
R> print(bdt) 
[1] "2001-02-15" 
R> 
19

También es posible usar

library(lubridate) 
dmy("1/1/2001") + days(45) 
9

Además de la simple adición demostrado por otros, también se puede utilizar seq.Date o seq.POSIXt encontrar otros incrementos o decrementos (la versión POSIXt hace segundos, minutos, hora, etc.):

> seq.Date(Sys.Date(), length=2, by='3 months')[2] 
[1] "2012-07-25" 
+1

para la referencia: para restar un año: 'seq.Date (Sys.Date(), longitud = 2, por = '-1 año')' –

Cuestiones relacionadas