我想要一个计算每月特定天数的函数.
即.2013年11月 - > 5周五..而13年12月将返回4周五..
有一个优雅的功能会返回这个?
library(lubridate)
num_days <- function(date){
x <- as.Date(date)
start = floor_date(x, "month")
count = days_in_month(x)
d = wday(start)
sol = ifelse(d > 4, 5, 4) #estimate that is the first day of the month is after Thu or Fri then the week will have 5 Fridays
sol
}
num_days("2013-08-01")
num_days(today())
Run Code Online (Sandbox Code Playgroud)
什么是更好的方法来做到这一点?
G. *_*eck 11
1)这d是输入,Date类对象,例如d <- Sys.Date().结果给出了包含的年/月的星期五数d.将5替换为1以获取星期一的数量:
first <- as.Date(cut(d, "month"))
last <- as.Date(cut(first + 31, "month")) - 1
sum(format(seq(first, last, "day"), "%w") == 5)
Run Code Online (Sandbox Code Playgroud)
2)用以下行替换最后一行.在这里,第一个术语是从下个月的第一个月或之后的大纪元到下个星期五的星期五,第二个星期是从大纪元到下一个星期五的星期五的数量d.月.同样,我们将所有5个替换为1,以获得星期一的计数.
ceiling(as.numeric(last + 1 - 5 + 4) / 7) - ceiling(as.numeric(first - 5 + 4) / 7)
Run Code Online (Sandbox Code Playgroud)
第二种解决方案稍长(尽管它具有相同的行数)但它具有矢量化的优点,即d可以是日期的矢量.
更新:添加第二个解决方案.