简体   繁体   English

R 中按组的时间序列预测

[英]Time Series Forecasting by Group in R

I have time series data grouped by US state from 2008-2018 and I need to forecast values for 2019-2020.我有 2008-2018 年按美国 state 分组的时间序列数据,我需要预测 2019-2020 年的值。 I tested the forecasting on Arizona and wrote something like this:我在亚利桑那州测试了预测并写了如下内容:

az <- subset(full_df, full_df$state == "AZ")

az$year <- lubridate::ymd(az$year, truncated = 2L)
az <- xts(az$variable, az$year)

forecast <- forecast(az, level = c(95), h = 2)

This works, producing two point estimates and their CIs.这有效,产生两点估计及其 CI。

My only issue is looping this over the entire original dataframe and producing the estimates for each state.我唯一的问题是在整个原始 dataframe 上循环并生成每个 state 的估计值。 Does anyone know how I would go about this?有谁知道我会如何 go 关于这个?

You can create a function, split and apply.您可以创建一个 function,拆分并应用。 I have not tested this as you did not include any data,我没有对此进行测试,因为您没有包含任何数据,

my_forecast_fun(df){
  df$year <- lubridate::ymd(df$year, truncated = 2L)
  df <- xts(df$variable, df$year)
  my_forecast <- forecast(df, level = c(95), h = 2) # avoid naming objects the same as functions (i.e. forecast)
  return(my_forecast)
}

my_list <- split(full_df, full_df$state)

res <- lapply(my_list, my_forecast_fun)

res is a list with the forecast for each state res是一个列表,其中包含每个 state 的预测

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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