Old Pro
Old Pro

Reputation: 25537

Calendar date arithmetic in R

Is there a way in R to do calendar arithmetic, e.g.

> as.Date('2014-03-30') - months(1)
[1] 2014-02-28

except in reality there's no such months function. This can be done with awareness of leap years and daylight savings time in SQL and Java, but I can't find a way to do it in R. I thought I'd get clever and use seq but no:

> seq(as.POSIXct('2014-03-30', tz='UTC'), by = '-1 months', length=2)[2]
[1] "2014-03-02 UTC"

Upvotes: 3

Views: 571

Answers (2)

rbatt
rbatt

Reputation: 4807

This is too long for an organized comment, but months is a function, and using as.POSIXlt (as opposed to ct) can allow for easy extraction of date attributes.

test <- as.POSIXlt('2014-03-30', tz='UTC')
attributes(test)$names
test$mon
months(test)

Given that test$mon returns a numeric value, it would be easy to perform arithmetic on the months. However, subtracting 1 month from January just gives you -1 (Jan is 0), and redefining test$mon <- test$mon - 1 doesn't seem to be of much help.

Nonetheless, depending on your application, the above information may still be useful.

Upvotes: -1

Dirk is no longer here
Dirk is no longer here

Reputation: 368191

Here is one way using RcppBDT which wraps (parts of) Boost Date_Time for use by R:

R> library(RcppBDT)
R> dt <- new(bdtDt, 2014, 3, 30)
R> dt
[1] "2014-03-30"
R> dt$addMonths(-1)
R> dt
[1] "2014-02-28"
R> 

Upvotes: 4

Related Questions