user1140126
user1140126

Reputation: 2649

How to 'update' a model built using 'glm' in R

In the reproducible code below (last line), the 'update' function doesn't work if I replace 'Income' with 'fieldToRemove'. How can I make this function work? I need to run that line in loop.

state.x77                          
tmpData = as.data.frame(state.x77) 
colnames(tmpData)[4] = "Life.Exp"  
colnames(tmpData)[6] = "HS.Grad"
cnames = colnames(tmpData)
cnames
lenCnames = length(cnames)

rhsOfFormula = paste(cnames[1:(length(cnames)-1)],collapse= "+")
lhsOfFormula = cnames[length(cnames)]
(fmla <- as.formula(paste(lhsOfFormula , " ~ ", rhsOfFormula )) )
modelTmp <- glm(formula = fmla, data=tmpData)

fieldToRemove = 'Income'
newModel <- update(modelTmp, .~.-Income )

Upvotes: 3

Views: 4847

Answers (1)

Jan van der Laan
Jan van der Laan

Reputation: 8105

update expects a formula as the second argument, so you have to use the same trick you used earlier: as.formula:

newModel <- update(modelTmp, as.formula(paste(".~.-", fieldToRemove)) )

Upvotes: 9

Related Questions