【问题标题】:calculate days per month between intervals in R计算R中间隔之间的每月天数
【发布时间】:2013-07-08 10:08:57
【问题描述】:

我有一个间隔的开始和结束日期列表,并且想计算间隔之间某个月内的总天数。

示例列表如下所示:

>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 来实现这一点,但只需要每月的天数,而不是特定年份的每月。非常感谢任何帮助。

卢卡斯

【问题讨论】:

    标签: r date intervals


    【解决方案1】:

    你可以这样做:

    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
    

    【讨论】:

      【解决方案2】:

      您可以尝试以下方法:

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

      【讨论】:

        猜你喜欢
        • 2012-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-12
        • 1970-01-01
        • 1970-01-01
        • 2019-03-27
        相关资源
        最近更新 更多