使用ts对象做移动平均时调用residuals函数报错的解决求助
Let's figure out what's causing this error and fix it right away.
First, let's break down the problem:
- You're using
ma()to generate a 3-period moving average on your training time series. - When you try
residuals(fixt_ma)or (more importantly)residuals$fixt_ma, you hit that atomic vector error.
Why this happens
- The
$operator mistake: Writingresiduals$fixt_mais incorrect becauseresidualsis a function, not a list or data frame. You can't use$to access elements of a function—this is the immediate cause of your error. - What
residuals(fixt_ma)returns: Thema()function (from theforecastpackage, I assume) returns a smoothed time series, not a formal model object (like what you'd get fromarima()). When you callresiduals()on this smoothed series, it returns an atomic vector (not a list), so even if you assigned it to a variable, you still couldn't use$on it.
The fix
Here's the straightforward way to calculate and work with your moving average residuals:
Calculate residuals directly (most reliable method):
Residuals for a moving average are just the original training values minus the smoothed moving average values. Since both are time series, you can subtract them directly:# Load the forecast package if you haven't already library(forecast) # Your existing moving average calculation fixt_ma <- ma(fixtures_training, 3) # Compute residuals manually (clean and clear) residuals_ma <- fixtures_training - fixt_ma # View the residuals residuals_maIf you still want to use
residuals():
If you prefer using theresiduals()function, assign its output to a variable first, then work with that variable (no$needed):# Get residuals and store them in a variable resid <- residuals(fixt_ma) # View the residuals resid
Quick check to confirm
You can verify the type of your fixt_ma object to make sense of this:
class(fixt_ma)
This should return "ts" (a time series object), not a model class like "Arima". That's why direct subtraction is more intuitive here—you're working with two time series, not a fitted model.
Once you have your residuals sorted, you can proceed to calculate accuracy with accuracy(fixt_ma, fixtures_test) as you originally planned.
内容的提问来源于stack exchange,提问作者Robin

