[R] finding the last day of the month

Gabor Grothendieck ggrothendieck at gmail.com
Mon Nov 8 14:07:20 CET 2010


On Mon, Nov 8, 2010 at 7:06 AM, Benjamin Williams <ben at bwmcct.com> wrote:
> Dear R Help,
>
> I am trying to get fields showing the last day of each month for a monthly
> closing project.  In order to find the last day of the previous month, I
> subtract the number of days from the current month. For all months my code
> works; however, for October, my code doesn't work...it returns
> 2010-09-*29* instead
> of 2010-09-*30*.
>
> format(strptime("2010-10-31",
> "%Y-%m-%d")-(as.numeric(format(as.Date("2010-10-31"),"%d"))*24*3600),"%Y-%m-%d")
>

There are many ways to do this but here is one using as.yearmon in
zoo.  This converts the Date variable, today, to "yearmon" class which
is a year and a fraction representing a month.  Then it converts it
back to "Date" class using frac = 1 which means all the way to the end
of the month (frac = 0, the default, means 1st of month, etc.):

> library(zoo)
> today <- Sys.Date()
> as.Date(as.yearmon(today), frac = 1)
[1] "2010-11-30"

If you are trying to show monthly data another option might be just to
not show the day at all:

> format(as.yearmon(today))
[1] "Nov 2010"
>
> # or without yearmon
> format(today, "%b %Y")
[1] "Nov 2010"




-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list