[英]Group by with the forecast package in R
我正在進行一些分析,希望對每個因素水平甚至多個因素(例如性別和年齡)進行預測。 到目前為止,我的過程是相當手動的,如下所示,對於一個具有2-5個級別的變量/因子來說,這很好。 但是,它無法伸縮以適應具有多個級別或多個因素的因素。
預測包中是否有任何類型的“分組依據”或“子集”功能會有所幫助? 我開始編寫程序以在最一般的情況下(即,在任意數量的因素和水平下)執行以下過程,但還不太成功。
順便說一句,很遺憾,我的數據是私人的,我不能在這里共享。 但這並不重要,因為下面的代碼有效,我正在尋找更好的,可擴展的解決方案。
# Example code
# category is a factor with levels A and B; amt is the variable to model/forecast
# using data.table syntax to create a vector for each category
vec1 <- dt[category == 'A']$amount
vec2 <- dt[category == 'B']$amount
# Create ts objects from above vectors
ts1 <- ts(vec1, start=c(start_year, start_month), end=c(end_year, end_month), frequency=12)
ts2 <- ts(vec2, start=c(start_year, start_month), end=c(end_year, end_month), frequency=12)
# Fit model
fit1 <- auto.arima(ts1, trace = TRUE, stepwise = FALSE)
fit2 <- auto.arima(ts2, trace = TRUE, stepwise = FALSE)
# Forecast out using selected models
h <- 12
fcast1 <- forecast(fit1, h)
fcast2 <- forecast(fit2, h)
# funggcast pulls out data from the forecast object into a df (needed for ggplot2)
# output columns are date, observed, fitted, forecast, lo80, hi80, lo95, hi95
fcastdf1 <- funggcast(ts1, fcast1)
fcastdf2 <- funggcast(ts2, fcast2)
# Add in category
fcastdf1$category <- 'A'
fcastdf2$category <- 'B'
# Merge into one df
df <- merge(fcastdf1, fcastdf2, all=T)
# Basic qplot from ggplot2 package, I am actually incorporating quite a bit more formatting but this is just to give an idea
qplot(x=date,
y=observed,
data=df,
color=category,
group=category, geom="line") +
geom_line(aes(y=forecast), col='blue')
您可以使用tapply
執行此操作:
res <- tapply(amount, category, function(x) {
ts <- ts(x, start = start, frequency = 12)
fit <- auto.arima(ts, trace = TRUE, stepwise = FALSE)
fcastdf <- forecast(fit, h = h)
return(fcastdf)
})
這將返回一個命名的預測列表。
您必須將開始日期設置為數據集中的最早日期。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.