view raw
R_User R_User - 8 months ago 22
R Question

Find out the number of days of a month in R

I have a date in P

date = as.Date("2011-02-23", "%Y-%m-%d")

Is it possible to find out the number of days of the month of that particular date? (With respect to leapyears). In PHP it would look similar to this (

days = format(date, "%t")

but "%t" seems to have a different meaning in R. Is there a solution for this problem?


You can write simple function to do that:

numberOfDays <- function(date) {
    m <- format(date, format="%m")

    while (format(date, format="%m") == m) {
        date <- date + 1

    return(as.integer(format(date - 1, format="%d")))

Invoke as:

> date = as.Date("2011-02-23", "%Y-%m-%d")
> numberOfDays(date)
[1] 28
> date # date is unchanged
[1] "2011-02-23"