2012-04-25 29 views

risposta

53

Usa +

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

Basta usare

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

dalla base R, o la funzionalità data in uno dei tanti pacchetti hanno contribuito. Il pacchetto RcppBDT include le funzionalità di Boost Date_Time che includono cose come "data del terzo mercoledì" in un determinato mese.

Edit: E incitati da @Andrie, ecco un po 'di più da RcppBDT (che è per lo più un banco di prova per i moduli Rcpp, in realtà).

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

Si potrebbe anche usare

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

Oltre alla semplice aggiunta dimostrato da altri, è anche possibile utilizzare seq.Date o seq.POSIXt per trovare altri incrementi o decrementi (la versione POSIXt fa secondi, minuti, ore, ecc.):

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

Per riferimento: per sottrarre un anno: 'seq.Date (Sys.Date(), length = 2, by = '-1 year')' –