ts(x)中的错误:“ ts”对象必须具有一个或多个观察值 [英] Error in ts(x) : 'ts' object must have one or more observations
问题描述
当我使用 forecast
库进行预测时,我注意到以下代码未按预期运行:
When I do forecast using forecast
library, I noticed following code does not run as expected:
library(forecast)
library(dplyr)
df1 <- data.frame(gp=gl(20,5), dt=seq(1:100))
get <- function (df1){
ts1 <- ts((df1%>%filter(gp==2))$dt)
as.numeric(forecast(ar(ts1),15)$mean)
}
print(get(df1))
错误返回为:
ts(x)中的错误:'ts'对象必须具有一个或多个观察结果
Error in ts(x) : 'ts' object must have one or more observations
可能是由 ar
引起的或 ar.burg
函数。因为如果将函数更改为 ets
或其他功能,则该函数会正常工作。
May be it is caused by ar
or ar.burg
function. Because if you change the function to ets
or something else the function works well.
更奇怪的是如果将代码更改为:
What is more strange is that if you change the code to:
library(forecast)
library(dplyr)
df1 <- data.frame(gp=gl(20,5), dt=seq(1:100))
ts1 <- ts((df1%>%filter(gp==2))$dt)
get <- function (ts1){
as.numeric(forecast(ar(ts1),15)$mean)
}
print(get(ts1))
代码也可以正常运行。我认为这可能是 ar
函数中的错误,问题与范围有关。有任何想法吗?
The code is also running correctly. I think this may be a bug in ar
function, and the problem is somehow related to scope. Any thoughts about this?
推荐答案
问题与范围界定有关。 forecast()
尝试查找用于拟合模型的时间序列。预测包中的函数(例如 ets
)将此信息存储在模型对象中,因此 forecast()$ c很容易$ c>来找到它。但是
ar()
来自stats包,它不存储用于拟合模型的时间序列。因此 forecast()
一直在寻找它。如果您在 get()
函数之外运行代码,则可以正常运行,因为 forecast()
设法找到了本地环境中的 ts1
对象。但是在 get()
函数中会导致错误。
The problem is to do with scoping. forecast()
tries to find the time series used to fit the model. The functions from the forecast package (such as ets
) store this information in the model object, so it is easy for forecast()
to find it. But ar()
is from the stats package, and it does not store the time series used to fit the model. So forecast()
goes looking for it. If you run your code outside of the get()
function, it works ok because forecast()
manages to find the ts1
object in the local environment. But within the get()
function it causes an error.
一个简单的解决方法是在调用 forecast
之前将信息添加到拟合模型中:
One simple fix is to add the information to the fitted model before calling forecast
:
library(forecast)
library(dplyr)
df1 <- data.frame(gp=gl(20,5), dt=seq(1:100))
ts1 <- ts((df1%>%filter(gp==2))$dt)
get <- function (ts1){
fit <- ar(ts1)
fit$x <- ts1
as.numeric(forecast(fit,15)$mean)
}
print(get(ts1))
或者,使用预测
而不是预测
:
library(dplyr)
df1 <- data.frame(gp=gl(20,5), dt=seq(1:100))
ts1 <- ts((df1%>%filter(gp==2))$dt)
get <- function (ts1){
fit <- ar(ts1)
as.numeric(predict(fit,n.ahead=15)$pred)
}
print(get(ts1))
这篇关于ts(x)中的错误:“ ts”对象必须具有一个或多个观察值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!