Search code examples
rlinear-regressionglm

Extract offset term from glm


I am wondering how to extract the offset term from the following model:

mod <- glm(cyl ~ mpg + disp + offset(log(gear)), family = "poisson", data = mtcars)

I would like to write a function get_offset() which returns the offset term:

get_offset <- function(x){
  ...
}

get_offset(mod)
#> "log(gear)"

get_offset() should also return the offset term for the models:

mod2 <- glm(cyl ~ mpg + disp, offset = log(gear), family = "poisson", data = mtcars)
mod3 <- glm(cyl ~ mpg + offset(log(gear)) + disp, family = "poisson", data = mtcars)
mod4 <- glm(cyl ~ mpg + offset(gear) + disp, family = "poisson", data = mtcars)

Giving:

get_offset(mod2)
#> "log(gear)"

get_offset(mod3)
#> "log(gear)"

get_offset(mod4)
#> "gear"

Created on 2021-01-02 by the reprex package (v0.3.0)


Solution

  • We could get the attributes from the terms

    get_offset <- function(model) {
         nm1 <- names(attributes(model$terms)$dataClasses)
          if('(offset)' %in% nm1) {
                 deparse(as.list(model$call)$offset)
            } else {
    
          sub("offset\\((.*)\\)$", "\\1", grep('offset', nm1, value = TRUE))
         }
       }
    
    get_offset(mod)
    #[1] "log(gear)"
    get_offset(mod2)
    #[1] "log(gear)"
    get_offset(mod3)
    #[1] "log(gear)"
    get_offset(mod4)
    #[1] "gear"