我需要创建一个随时间变化的递归过滤器。
stats::filter
中实现的经典过滤器具有以下形式:
Y [t] = X [t] + b 1 * Y [t-1] + b [2] * Y [t-2] + ....
但是,我想创建一个根据t
恰好是星期几而变化的过滤器,所以:
Y [t] = X [t] + b [day_of_week(t),1] * Y [t-1] + b [day_of_week(t),2] * Y [t-2] + ...
作为stats::filter
不支持的额外复杂功能,我还需要调整第一项的系数:
Y [t] = b [day_of_week(t),0] * X [t] + b [day_of_week(t),1] * Y [t-1] + b [day_of_week(t),2] * Y [t-2] + ...
以下是一个示例数据集,说明了需求:
library(dplyr)
parameters = matrix(data = runif(14), nrow = 7, ncol = 2,
dimnames = list(c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
c("same_day_impact", "previous_day_impact")))
df_x = data_frame(date = seq.Date(from = as.Date("2015-01-01"),
to = as.Date("2015-12-31"),
by = "day")) %>%
mutate(series = rnorm(n()),
series_lag = lag(series, 1, default = 0),
day_of_week = wday(date),
day_of_week_name = wday(date, label = TRUE),
same_day_impact = parameters[day_of_week, 1],
previous_day_impact = parameters[day_of_week, 2])
所以,我想要same_day_impact*series + previous_day_impact*.
,其中.
表示过滤器的结果直到上一个时间点。
我基本上正在寻找一种巧妙的方法来实现这一目标。欢迎任何帮助。