Search code examples
rmodelglmlmgamma-distribution

Calculating working residuals of a Gamma GLM model


I am trying to calculate the working residuals of a Gamma GLM model. I'm doing this manually because I want to calculate the partial residuals step-by-step. My model and its coefficients and predictions are described below:

library(datasets)
data(mtcars)

model <- glm(mpg ~ cyl + disp + hp, data=mtcars, family=Gamma)
coefs <- coef(model)
pred <- coefs[1] + coefs[2]*mtcars$cyl + coefs[3]*mtcars$disp + coefs[4]*mtcars$hp

I tried to calculate the working residuals by applying the formula (value - fitted.value)/fitted.value , which works fine for a Poisson glm. However, it didn't work for Gamma since the values differ from those I generate using the function resid():

(mtcars$mpg - (-pred^(-1)))/-pred^(-1))
resid(model, type="working")

Does anybody know how to estimate such working residuals to then calculate the partial residuals?


Solution

  • The working residuals are just model$residuals. See ?glm


    ## setup
    library(datasets)
    data(mtcars)
    model <- glm(mpg ~ cyl + disp + hp, data = mtcars, family = Gamma)
    
    ## family info
    oo <- Gamma(link = "inverse")
    
    ## compute linear predictor manually (assuming no model offset)
    coefs <- coef(model)
    eta <- coefs[1] + coefs[2] * mtcars$cyl + coefs[3] * mtcars$disp +
           coefs[4] * mtcars$hp
    
    ## compute working residuals
    resi_working <- (mtcars$mpg - oo$linkinv(eta)) / oo$mu.eta(eta)
    
    ## validation
    range(resi_working - model$residuals)
    #[1] 0 0