Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out the number of days of a month in R

Tags:

date

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?

like image 736
R_User Avatar asked Jun 05 '11 13:06

R_User


People also ask

How many days are in a year r?

In the Gregorian Calendar, a common year has 365 days.


2 Answers

lubridate package has required function "days_in_month" with respect to leapyears.

Your example:

    date <- as.Date("2011-02-23", "%Y-%m-%d")     lubridate::days_in_month(date)     # Feb     # 28 

Leap year (2016):

    date_leap <- as.Date("2016-02-23", "%Y-%m-%d")     lubridate::days_in_month(date_leap)     # Feb      # 29 
like image 62
George Shimanovsky Avatar answered Oct 05 '22 13:10

George Shimanovsky


The Hmisc library has a couple of helpful functions for doing this:

require(Hmisc) monthDays(as.Date('2010-01-01')) 
like image 36
yoni Avatar answered Oct 05 '22 14:10

yoni