预测 R 中未来时间序列的平均值

Predicting the averages of future time series in R

这是我的示例数据:

df <- structure(list(Make = c("Ford", "Nissan", "Volkswagen", "Chevrolet", 
"Chevrolet", "GMC", "Mazda", "Ford", "Chevrolet", "Ford", "Cadillac", 
"Ford", "Grand Cherokee", "Volkswagen", "Chevrolet", "Toyota", 
"Toyota", "Honda", "Toyota", "Audi"), Model = c(2011L, 2011L, 
2012L, 2011L, 2010L, 2011L, 2010L, 2010L, 2012L, 2012L, 2012L, 
2010L, 2010L, 2010L, 2011L, 2010L, 2010L, 2011L, 2011L, 2011L
), Highway_mpg = c(15L, 20L, 27L, 20L, 23L, 25L, 26L, 17L, 26L, 
25L, 27L, 21L, 20L, 30L, 21L, 18L, 28L, 26L, 20L, 19L), City_mpg = c(11L, 
16L, 21L, 14L, 17L, 18L, 20L, 12L, 16L, 18L, 18L, 15L, 14L, 22L, 
15L, 14L, 19L, 17L, 15L, 12L)), row.names = c(NA, -20L), class = ("data.frame"))

这是我的期望输出(假设 NA 是预测值):

我想计算每个车型年份的平均油耗,同时还预测 2013 年至 2016 年的平均值。

我试过的:

我尝试使用以下代码跟随对 this question 的回答:

cars_model <- lm(Model ~ Highway_mpg + City_mpg, data = df)

years <- data.frame(Model = c(2013:2016))

res <- predict(cars_model, years)

Error in eval(predvars, data, env) : object 'Highway_mpg' not found

阅读错误后,我尝试将油耗列添加到我的新df中,但仍然出现错误。

您使用 Highway_mpgCity_mpg 预测 。如果你想要像上面那个蓝色 table 这样的结果,并且因为你关注 每个车型年份的平均油耗 ,你最好尝试这种方式。

mod1 <- lm(Highway_mpg ~ Model, data = dummy)
mod2 <- lm(City_mpg ~ Model, data = dummy)
years <- data.frame(Model = c(2013:2016))

data.frame(
  Model = years$Model,
  Highway_mpg = predict(mod1, years),
  City_mpg = predict(mod2, years)
  
)

  Model Highway_mpg City_mpg
1  2013    25.21429 17.14286
2  2014    26.35714 17.57143
3  2015    27.50000 18.00000
4  2016    28.64286 18.42857