You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ts对象做移动平均时调用residuals函数报错的解决求助

Fixing "$ operator is invalid for atomic vectors" When Working with Moving Average Residuals in R

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

  1. The $ operator mistake: Writing residuals$fixt_ma is incorrect because residuals is 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.
  2. What residuals(fixt_ma) returns: The ma() function (from the forecast package, I assume) returns a smoothed time series, not a formal model object (like what you'd get from arima()). When you call residuals() 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:

  1. 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_ma
    
  2. If you still want to use residuals():
    If you prefer using the residuals() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:47:59