model.frame.default中的错误:可变长度不同 [英] Error in model.frame.default: variable lengths differ
问题描述
在使用mgcv软件包运行gam模型时,遇到了我无法理解的奇怪错误消息:
On running a gam model using the mgcv package, I encountered a strange error message which I am unable to understand:
"model.frame.default中的错误(公式=死亡〜pm10 + Lag(resid1,1)+:可变长度不同(为'Lag(resid1,1)'找到)".
"Error in model.frame.default(formula = death ~ pm10 + Lag(resid1, 1) + : variable lengths differ (found for 'Lag(resid1, 1)')".
在model1中使用的观测次数与偏差残差的长度完全相同,因此我认为此错误与数据大小或长度的差异无关.
The number of observations used in model1 is exactly the same as the length of the deviance residual, thus I think this error is not related to difference in data size or length.
我在网上此处,但该帖子未收到足够的答案,因此对我的问题没有帮助.
I found a fairly related error message on the web here, but that post did not receive an adequate answer, so it is not helpful to my problem.
可复制的示例和数据如下:
Reproducible example and data follows:
library(quantmod)
library(mgcv)
require(dlnm)
df <- chicagoNMMAPS
df1 <- df[,c("date","dow","death","temp","pm10")]
df1$trend<-seq(dim(df1)[1]) ### Create a time trend
运行模型
model1<-gam(death ~ pm10 + s(trend,k=14*7)+ s(temp,k=5),
data=df1, na.action=na.omit, family=poisson)
获得偏差残差
resid1 <- residuals(model1,type="deviance")
为模型1添加一天滞后的偏差
model1_1 <- update(model1,.~.+ Lag(resid1,1), na.action=na.omit)
model1_2<-gam(death ~ pm10 + s(trend,k=14*7)+ s(temp,k=5) + Lag(resid1,1), data=df1,
na.action=na.omit, family=poisson)
这两个模型都产生了相同的错误消息.
Both of these models produced the same error message.
推荐答案
Joran建议在运行模型之前先删除NA.因此,我删除了NA,运行模型并获得了残差.当我通过包含滞后残差来更新model2时,错误消息不再出现.
Joran suggested to first remove the NAs before running the model. Thus, I removed the NAs, run the model and obtained the residuals. When I updated model2 by inclusion of the lagged residuals, the error message did not appear again.
df2<-df1[complete.cases(df1),]
运行主模型
model2<-gam(death ~ pm10 + s(trend,k=14*7)+ s(temp,k=5), data=df2, family=poisson)
获得残差
resid2 <- residuals(model2,type="deviance")
通过添加滞后1残差来更新model2
model2_1 <- update(model2,.~.+ Lag(resid2,1), na.action=na.omit)
这篇关于model.frame.default中的错误:可变长度不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!