繁体   English   中英

通过R中的预测包进行分组

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM