2015-04-03 58 views
2

我在尝试测试模型的准确性时收到了上述消息。计划是预测最后15个时间点,并将它们与实际的误差值进行比较,但出于某种原因,我得到了“可变长度差异”错误消息。在预测中收到“可变长度差异”错误

这是使用来自astsa包的johnson和johnson数据(数据(jj))。下面是代码和相关错误 -

> ##set up JJ data and time because its quarterly data 
> X.all<-jj[1:84] 
> t<-time(jj) 
> 
> values<-length(t)-15 
> ts<-t[1:values] 
> tsq<-ts^2/factorial(2) 
> X<-X.all[1:values] 
> year.first<-values+1 
> year.last<-length(t) 
> ##setting t for 15 values using quarterly idea 
> new<-data.frame(ts=t[year.first:year.last]) 
> X.true<-X.all[(values+1):length(t)] 
> fit1<-lm(X~ts+tsq) 
> Xhat<-predict(fit1,new,se.fit=TRUE) 
Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) : 
    variable lengths differ (found for 'tsq') 
In addition: Warning message: 
'newdata' had 15 rows but variables found have 69 rows 

> X.hat<-round(Xhat$fit,2) 
> error<-X.true-X.hat 

回答

2

的问题是,你想叫predictnewdata的论点,即不包含所有在模型中使用的变量。 new只包含ts,而不包含tsq。你可以解决这个问题的:

  1. 创建包含两种tstsq,或
  2. 更好的解决方案是使用你的型号规格I()符号,就像定义tsq一data.frame newlm(X ~ ts + I(ts^2/factorial(2)))I()表示法会自动生成转换,因此您不必手动创建功率术语等,只需将它们包含在您的规范中即可。

举个例子,你可以尝试这一点与iris数据集,看看它是如何工作比你目前的做法更好:

fit1 <- lm(Sepal.Length ~ Sepal.Width + I(Sepal.Width^2/factorial(2)), data = iris) 
new <- data.frame(Sepal.Width = seq(1,5,by = 0.25)) 
predict(fit1, new) 

我们可以比较这对你的方法,观察你的错误”重新遇到:

s2 <- I(iris$Sepal.Width^2/factorial(2)) 
fit1 <- lm(Sepal.Length ~ Sepal.Width + s2, data = iris) 
new <- data.frame(Sepal.Width = seq(1,5,by = 0.25)) 
predict(fit1, new) 
# Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) : 
# variable lengths differ (found for 's2') 
# In addition: Warning message: 
# 'newdata' had 17 rows but variables found have 150 rows 
+0

非常感谢你 - 你是一个拯救生命的人! – MattLH 2015-04-03 21:40:47

+0

@MattLH你能把这个标记为答案吗?这可能对一群民众有用。 – Navneet 2015-08-11 16:28:46