R 如何为特定范围生成(业务)月底/月初?
我感兴趣的是为一段时间生成一系列的月底或月初。如果日期是工作日,而不是星期天或星期六,那就更好了。在R中如何实现这一点?我在该任务中使用了两个函数:R 如何为特定范围生成(业务)月底/月初?,r,R,我感兴趣的是为一段时间生成一系列的月底或月初。如果日期是工作日,而不是星期天或星期六,那就更好了。在R中如何实现这一点?我在该任务中使用了两个函数: library(lubridate) # returns a sequence of Business Month Ends between two inputs (inclusive) # or for the one input GetBizMonthEndFor <- function(dateChar1, dateChar2 = d
library(lubridate)
# returns a sequence of Business Month Ends between two inputs (inclusive)
# or for the one input
GetBizMonthEndFor <- function(dateChar1, dateChar2 = dateChar1){
# generate the sequence of month starts
dateChar <- seq(floor_date(as.Date(dateChar1), unit = "month"),
floor_date(as.Date(dateChar2), unit = "month"),
by = "month")
# add a month to each sequence element and subtract a day
dateChar <- dateChar + months(1) - days(1)
# if the day is saturday or sunday, subtract a day or two to hit the
# previous friday
dateChar[wday(dateChar) == 1] <- dateChar[wday(dateChar) == 1] - days(2)
dateChar[wday(dateChar) == 7] <- dateChar[wday(dateChar) == 7] - days(1)
dateChar
}
# returns a sequence of Business Month Starts between two inputs (inclusive)
# or for the one input
GetBizMonthStartFor <- function(dateChar1, dateChar2 = dateChar1){
# generate the sequence of month starts
dateChar <- seq(floor_date(as.Date(dateChar1), unit = "month"),
floor_date(as.Date(dateChar2), unit = "month"),
by = "month")
# January 1 is a holiday, so if the month start is january 1, make
# January 2 the business month start
dateChar[month(dateChar) == 1 & day(dateChar) == 1] <-
dateChar[month(dateChar) == 1 & day(dateChar) == 1] + days(1)
# If the day is a saturday or sunday, add a day or two to hit the next
# monday
dateChar[wday(dateChar) == 1] <- dateChar[wday(dateChar) == 1] + days(1)
dateChar[wday(dateChar) == 7] <- dateChar[wday(dateChar) == 7] + days(2)
dateChar
}
请注意,输入日期的日期并不重要,它需要输入的月份,并将它们更改为月份序列的结束。我还没有把逻辑放进去,使它们只包括输入值之间的月末/开始日期,但这不是一个很难解决的问题。不过,增加了一项功能,即只需使用一个输入而不是两个输入,即可检查日期的月底/月初
> GetBizMonthStartFor("2015-11-01")
[1] "2015-11-02"
> GetBizMonthStartFor("2015-11-01")
[1] "2015-11-02"