R_User R_User - 1 year ago 51
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 (http://www.php.net/manual/en/function.date.php):

days = format(date, "%t")

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

Answer Source

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"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download