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

R代码报错Error in match.arg(opt.crit):求修正及运行方法

修正多伦多气温预测R代码的错误

错误原因分析

报错Error in match.arg(opt.crit) : 'arg' must be NULL or a character vector是因为调用itsmr包的forecast函数时,传入的opt参数为数值0,但该参数要求传入字符向量(指定优化准则,可选值为"css"或"mle"),不符合参数类型要求。

修正后的完整代码

library(forecast)
library(itsmr)
tor = readRDS("/Users/zehaoli/Desktop/TorontoWeather.rds")

# 提取目标时间段气温数据
tempMay1.7 <- subset(tor, tor$Date.Time >= "2003-05-01 00:00" &
                       tor$Date.Time <= "2003-05-07 23:00")$Temp
tempMay8 <- subset(tor, tor$Date.Time >= "2003-05-08 00:00" &
                     tor$Date.Time <= "2003-05-08 23:00")$Temp

# 构建模型并预测
M <- c("season",24,"trend",2) 
tesname <- Resid(tempMay1.7, M) 
a <- arma(tesname, 1, 1) 
# 修正opt参数为合法的字符值,这里用最小二乘准则"css"
f <- forecast(tempMay1.7, M, a, h=24, opt="css")

# 绘制预测对比图
plot(1:192,c(tempMay1.7,rep(NA,24)),
     type="l",col="blue",ylim=c(3,22),ylab="Temp(°C)",
     xlab="Date",main="Toronto Temperature (May 1 - May 8,2003)",
     xaxt="n")
# 修正轴标签的拼写错误
axis(side=1,at=12+(0:7)*24,
     labels=c("May1","May2","May3","May4","May5","May6","May7","May8"))

lines(169:192,f$pred,col="red")
lines(169:192,f$l,lty=2,col="green")
lines(169:192,f$u,lty=2,col="green")
lines(169:192,tempMay8,col="black")

额外修正说明

  1. 参数修正:将opt=0替换为opt="css"(最小二乘估计)或opt="mle"(极大似然估计),二者均为itsmr::forecast函数接受的合法参数值;若无需手动指定优化准则,也可直接省略opt参数,使用函数默认值。
  2. 图表细节修正:修正了轴标签中的拼写错误(如Мау6→May6、May?→May7、Ma8→May8),确保图表显示正确。

内容的提问来源于stack exchange,提问作者zehao li

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 12:32:23