Calculating days per month between interval of two dates

限于喜欢 提交于 2019-12-01 18:12:01

This is not necessarily efficient because it creates a sequence of days, but it does the job:

> library(zoo)
> table(as.yearmon(seq(event_start_date, event_end_date, "day")))

Oct 2012 Nov 2012 Dec 2012 Jan 2013 Feb 2013 
       9       30       31       31        7

If your time span is so large than this method is slow, you'll have to create a sequence of firsts of the months between your two (truncated) dates, take the diff, and do a little extra work for the end points.

As DjSol already pointed out in his comment, you can just subtract two dates to get the number of days:

event_start_date <- as.Date("23/10/2012", "%d/%m/%Y")
event_end_date   <- as.Date("07/02/2013", "%d/%m/%Y")
as.numeric(event_end_date - event_start_date)

Is that what you want? I have the feeling that you might have more of a problem to get the start and end date in such a format so you can easily subtract them because you mention a loop. If so, however, I guess we need more details on how your actual data looks.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!