Here are a couple of approaches. Both approaches are vectorized, i.e. the input x
can be a single "Date"
class date or a vector of such dates.
1) This converts the input date, x
, into a "yearmon"
object and then converts it back to the last of the month and first of the month and subtracts the two adding 1.
x <- Sys.Date() # use today as the test date
library(zoo)
ym <- as.yearmon(x)
as.Date(ym, frac = 1) - as.Date(ym) + 1
## Time difference of 30 days
or for a numeric result use:
as.numeric(as.Date(ym, frac = 1) - as.Date(ym) + 1)
## [1] 30
1a) A variation would be:
as.Date(ym + 1/12) - as.Date(ym)
## Time difference of 30 days
or for a numeric result:
as.numeric(as.Date(ym + 1/12) - as.Date(ym))
## [1] 30
2) This is a base solution. First we define fom
which inputs a "Date"
vector and returns the first of the month of each component. Now we just take the difference between the first of the next month and the first of the current month.
fom <- function(x) as.Date(cut(x, "month"))
fom1 <- fom(x)
fom2 <- fom(fom1 + 32)
as.numeric(fom2 - fom1)
## [1] 30