我想编写自己的预测函数,分配forecast
对象,并使用该对象的预测包中的use函数。我尝试通过以下方式(使用这种方法How to create a forecast object in R)复制meanf函数:
myfun <- function(x, h, ...)
{
# Compute some forecasts
fc <- rep(mean(x), h)
# Construct output list
output <- list(mean=fc, x=x, ...)
# Return with forecasting class
return(structure(output, class='forecast'))
}
但是当我应用精度函数时:
# sample dataset
price <- c(351.75, 347, 348, 342, 339, 339.86, 342.61, 345, 340, 336.11,
331, 333.94, 330.01, 317, 313, 313.98, 315, 319.45, 313, 316,
316.5, 315, 320, 315, 311.23, 305.55, 298.02, 291.8, 294.98,
296.44, 296, 294, 290.65, 288, 291.99, 295, 310, 303.1, 306.11,
309.51, 312.51, 328.1, 328.1, 324.8, 329.23, 337.01, 333.6, 333,
327.23, 328.5, 328.54, 324.5, 322, 317.01, 318, 319.98, 329.8,
323, 317, 318.55, 319.98, 323.99, 316.09, 315.01, 317.5, 315.03,
312.55, 312, 315, 312.89, 308.5, 295.53, 308, 315, 285.12, 284.34,
285, 281.39, 282.92, 285.94, 284.96, 282.9, 273.5, 273.5, 273.21,
281.14, 286.99, 283, 280.39, 283, 280, 285, 285.02, 289, 288,
284.5, 280.83, 278.3, 274.1, 276)
price <- ts(price, start = 1, frequency = 1)
train <- subset(price, end = length(price) - 10)
test <- subset(price, start = (length(price) + 1) - 10)
# my forecast function
myfun <- function(x, h, ...)
{
# Compute some forecasts
fc <- rep(mean(x), h)
# Construct output list
output <- list(mean=fc, x=x, ...)
# Return with forecasting class
return(structure(output, class='forecast'))
}
# aplpy function and accuracy
myMean <- myfun(train, 10)
accuracy(myMean, test)
它返回错误:
NextMethod(.Generic)中的错误:无法将'tsp'分配给零长度 向量
我不明白此错误?
答案 0 :(得分:1)
问题是您的output
没有适合的值元素。这很重要,因为forecast:::accuracy.default()
调用forecast:::trainingaccuracy()
,而后者依次调用fitted()
,并尝试从时间序列对象中减去结果。当fitted()
的结果为NULL
时,您将收到该错误。我们可以通过修改myMean()
来解决它:
myfun <- function(x, h, ...)
{
# Compute some forecasts
xmean <- mean(x)
fc <- rep(xmean, h)
fitted.values <- rep(xmean, length(x))
# Construct output list
output <- list(mean=fc, x=x, fitted.values=fitted.values, ...)
# Return with forecasting class
return(structure(output, class='forecast'))
}
# aplpy function and accuracy
myMean <- myfun(train, 10)
accuracy(myMean, test)
# ME RMSE MAE MPE MAPE MASE
# Training set -1.388816e-14 19.61672 15.93970 -0.4032892 5.180507 3.718275
# Test set -2.989633e+01 30.27324 29.89633 -10.6303518 10.630352 6.973957
# ACF1 Theil's U
# Training set 0.9181787 NA
# Test set 0.6992239 9.267271