R: How to update model frame after reducing model formula

旧时模样 提交于 2019-12-11 11:37:12

问题


I am working a phylogenetic multiple regression using the caper package on Windows 7, and am receiving a Model frame / formula mismatch error consistently when ever I try to graph a residual leverage plot after generating a reduced model.

Here is the minimal code needed to reproduce the error:

 g <- Response ~ (Name1 + Name2 + Name3 + Name4 + Name5 + Name6 + Name7)^2 + Name1Sqd
 + Name2Sqd + Name3Sqd + Name4Sqd + Name5Sqd + Name6Sqd + Name7Sqd

 crunchMod <- crunch(g, data = contrasts)
 plot(crunchMod, which=c(5)) ####Works just fine####

 varName <- row.names(summary(crunchMod)$coefficients)[1]
 #it doesn't matter which predictor I remove.

 Reduce(paste, deparse(g))
 g <- as.formula(paste(Reduce(paste, deparse(g)), as.name(varName), sep=" - "))
 #Edits the model formula to remove varName

 crunchMod <- crunch(g, data = contrasts)
 plot(crunchMod, which=c(5)) ####Error Happens Here####

When I try to graph a residual leverage plot to look at the effects of model complexity, I get the following error:

Error in model.matrix.default(object, data = list(Response = c(-0.0458443124730482,
: model frame and formula mismatch in model.matrix()

The code that starts this error is: plot(crunchMod, which=c(5)) where crunchMod
holds my regression model via crunchMod <- crunch(g, data = contrasts) from the
caper Package on Windows 7 OS.

How can I update my model frame to be able to examine cook's distance again (either graphically or numerically)?


回答1:


Within the source code of crunch() there was the implementation:

    data <- subset(data, select = all.vars(formula)) 

which has the side effect of making all interaction effects from a deleted primary effect invalid in the model frame. This becomes more apparent when one realizes that plotting cook's distance vs leverage will work if he/she only deletes interaction effects.

Thus to solve this problem, all interaction effects must be included in the original data frame before calling crunch() to create a linear model. While this makes transforming the data slightly more complicated, it is easy to add these interactions following these two links:

Generating interaction variables in R dataframes (second answer down)

http://www.r-bloggers.com/type-conversion-and-you-or-and-r/



来源:https://stackoverflow.com/questions/28399090/r-how-to-update-model-frame-after-reducing-model-formula

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!