为您提供一些背景信息。我正在尝试创建一个事件日历,以控制重复事件,例如假期(主要是美国的假期)。
我还想指出所说假期的天数(周,月甚至季度)变化。例如,复活节在2024年的第一季度下降,而在第二年(2025年)的第二季度下降。以下是我尝试将此逻辑转换为代码的尝试(仅适用于当年与下一年或上一年之间的同比数字)。需要工作的列是 “ ShiftInHoliday”。
如何动态标记假期的变化,以便可以将上述复活节的变化记录在所有未来日期的数据集中,并与往年进行比较?
if (!require(timeDate)) install.packages("timeDate", quiet = TRUE)
if (!require(dplyr)) install.packages("dplyr", quiet = TRUE)
currentYear <- getRmetricsOptions("currentYear")
mainly_us_holidays <- subset(listHolidays(), grepl("US|CA|FR|GB|CaR", listHolidays()) == TRUE)
all <- c(mainly_us_holidays, c("Easter", "EasterSunday", "EasterMonday"), mainly_us_holidays)
holiday_mapped <-
do.call(rbind,
lapply(all, function(i){
foo <- match.fun(i)
data.frame(all = i,
dates = as.Date(foo(2017:2030)))
}))
holiday_mapped$all <-
ifelse(substr(holiday_mapped$all, 1, 2) %in% c("CA") | substr(holiday_mapped$all, 1, 3) %in% c("CaR"), paste0("Canada:", holiday_mapped$all),
ifelse(substr(holiday_mapped$all, 1, 2) %in% "FR", paste0("France:", holiday_mapped$all),
ifelse(substr(holiday_mapped$all, 1, 2) %in% "GB", paste0("Great Britain:",holiday_mapped$all),
paste0("US:", holiday_mapped$all ))))
holiday_mapped <- holiday_mapped %>% group_by(all) %>% arrange(all) %>% mutate(dateDiff_Holiday = diff(c(NA, dates)))
holiday_mapped$HolidayShiftFlag <- ifelse(abs(holiday_mapped$dateDiff_Holiday) %% 365 %in% c(0, 1, c(359:364, 366:371)), 0,
ifelse(holiday_mapped$all == "Non-Holiday", 0, ifelse(is.na(holiday_mapped$dateDiff_Holiday) == TRUE, 0, 1)))
holiday_mapped$ShiftInHoliday <-
ifelse( holiday_mapped$HolidayShiftFlag == 1 & (holiday_mapped$dateDiff_Holiday - 365) < 0,
paste(holiday_mapped$all, "Shifts", abs(holiday_mapped$dateDiff_Holiday - 365), "Days Backward", "|",
round(abs(holiday_mapped$dateDiff_Holiday - 365) / 7, 2), "Weeks"),
ifelse(holiday_mapped$HolidayShiftFlag == 1 & (holiday_mapped$dateDiff_Holiday - 365) > 0, paste(holiday_mapped$all, "Shifts",
abs(holiday_mapped$dateDiff_Holiday - 365), "Days Forward", "|", round((abs(holiday_mapped$dateDiff_Holiday - 365)) / 7, 2), "Weeks"), NA ))
谢谢您的帮助。
答案 0 :(得分:0)
我太复杂了。我只是简单地使用基数R重用了diff()函数,但是这次在几天和几周内获得了几天和几周的同比变化(推断了月和季度)。谢谢您抽出宝贵时间给那些尝试的人!