Reputation: 727
I have a list of start and end dates of intervals and would like to calculate the total number of days within a certain month between the intervals.
An example list would look like this:
>dates
open close
1 11/01/2004 29/01/2004
2 30/01/2004 17/02/2004
3 11/01/2006 26/01/2006
4 27/01/2006 11/02/2006
5 11/01/2007 26/01/2007
6 27/01/2007 11/02/2007
7 18/02/2004 07/03/2004
8 12/02/2006 27/02/2006
9 28/02/2006 15/03/2006
10 12/02/2007 27/02/2007
(which can be easily converted to dates) and I would like to get per interval the number of days within every month. Something like this:
jan feb mar apr may jun jul aug sep oct nov dec
19
2 17
16
5 11
16
5 11
12 7
16
1 15
I have tried using as.yearmon to achieve this, but only need the days per month, not per month of a specific year. Any help is much appreciated.
Lukas
Upvotes: 1
Views: 315
Reputation: 121578
You can do something like this :
dt$open <- as.Date(dt$open,format='%d/%m/%Y')
dt$close <- as.Date(dt$close,format='%d/%m/%Y')
mapply(function(x,y)
{
vv <- vector('integer',12)
names(vv) <- c(paste0('0',1:9),10:12)
ff <- table(format(seq(x,y,1),'%m'))
vv[names(ff)] <- ff
vv
},
dt$open,dt$close)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
01 19 2 16 5 16 5 0 0 0 0
02 0 17 0 11 0 11 12 16 1 16
03 0 0 0 0 0 0 7 0 15 0
04 0 0 0 0 0 0 0 0 0 0
05 0 0 0 0 0 0 0 0 0 0
06 0 0 0 0 0 0 0 0 0 0
07 0 0 0 0 0 0 0 0 0 0
08 0 0 0 0 0 0 0 0 0 0
09 0 0 0 0 0 0 0 0 0 0
10 0 0 0 0 0 0 0 0 0 0
11 0 0 0 0 0 0 0 0 0 0
12 0 0 0 0 0 0 0 0 0 0
Upvotes: 1
Reputation: 11
You could try something like the following:
apply(as.Dates(dates), 1, function(x) {
dts <- seq(x[1], x[2], by=1)
m <- format(dts, "%m")
table(m)
})
Upvotes: 1