簡體   English   中英

計算R中的間隔之間每月的天數

[英]calculate days per month between intervals in R

我有間隔的開始和結束日期列表,並想計算間隔之間某個月內的總天數。

示例列表如下所示:

>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  

(可以輕松將其轉換為日期),我希望每個時間間隔獲取每個月內的天數。 像這樣:

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

我嘗試使用as.yearmon來實現這一點,但只需要每月的天數,而不需要特定年份的每個月的天數。 任何幫助深表感謝。

盧卡斯

您可以嘗試以下操作:

apply(as.Dates(dates), 1, function(x) {
    dts <- seq(x[1], x[2], by=1)
    m <- format(dts, "%m")
    table(m)
})

您可以執行以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM