两个日期之间每月的天数

No of monthly days between two dates

diff(seq(as.Date("2016-12-21"), as.Date("2017-04-05"), by="month"))
Time differences in days
[1] 31 31 28

以上代码生成 Dec、Jan 和 Feb 月的天数。 但是,我的要求如下

#Results that I need
#monthly days from date 2016-12-21 to 2017-04-05 
11, 31, 28, 31, 5
#i.e 11 days of Dec, 31 of Jan, 28 of Feb, 31 of Mar and 5 days of Apr.

我什至从 lubridate 尝试了 days_in_month 但没能达到结果

library(lubridate)    
days_in_month(c(as.Date("2016-12-21"), as.Date("2017-04-05")))
Dec Apr 
 31  30 

试试这个:

x = rle(format(seq(as.Date("2016-12-21"), as.Date("2017-04-05"), by=1), '%b'))

> setNames(x$lengths, x$values)
# Dec Jan Feb Mar Apr 
#  11  31  28  31   5 

虽然我们已经看到用 rle 巧妙地替换 table 和纯 table 解决方案,但我想添加两种使用分组的方法。所有方法的共同点是,它们在两个给定日期之间创建一系列天数,并按月汇总,但方式不同。

aggregate()

这个使用基数 R:

# create sequence of days
days <- seq(as.Date("2016-12-21"), as.Date("2017-04-05"), by = 1)
# aggregate by month
aggregate(days, list(month = format(days, "%b")), length)
#  month  x
#1   Apr  5
#2   Dez 11
#3   Feb 28
#4   Jan 31
#5   Mrz 31

不幸的是,月份是按字母顺序排列的,因为它发生在简单的 table() 方法中。在这些情况下,我确实更喜欢 ISO8601 明确命名月份的方式:

aggregate(days, list(month = format(days, "%Y-%m")), length)
#    month  x
#1 2016-12 11
#2 2017-01 31
#3 2017-02 28
#4 2017-03 31
#5 2017-04  5

data.table

现在我已经习惯了 data.table 语法,这是我的首选方法:

library(data.table)
data.table(days)[, .N, .(month = format(days, "%b"))]
#   month  N
#1:   Dez 11
#2:   Jan 31
#3:   Feb 28
#4:   Mrz 31
#5:   Apr  5

月份的顺序保持在输入向量中出现的顺序。