Search code examples
rlminteraction

How to present R lm object interaction coefficients in a table?


Consider an lm fit object with interaction terms, e.g.:

Call:
lm(formula = mpg ~ interaction(gear, am, drop = T) - 1 + cyl, data = mtcars)

Coefficients:
interaction(gear, am, drop = T)3.0  interaction(gear, am, drop = T)4.0  
                            35.478                              34.022  
interaction(gear, am, drop = T)4.1  interaction(gear, am, drop = T)5.1  
                            37.949                              36.946  
                               cyl  
                            -2.594  

Is there a straightforward way to arrange the coefficients of (only) the interaction-terms in a two-dimensional table? e.g.:

gear    am = 0   am = 1   
3       35.478   NA   
4       34.022   37.949
5       NA       36.946

Solution

  • You can use the broom package to get the information easily. It's just a matter of adjusting the table you get to suit your needs:

    model <- lm(formula = mpg ~ interaction(gear, am, drop = T) - 1 + cyl, data = mtcars)
    
    library(broom)
    tidy(model)[grep("interaction", tidy(model)$term),]
    #                                term estimate std.error statistic      p.value
    #1 interaction(gear, am, drop = T)3.0 35.47755  3.533483  10.04039 1.302118e-10
    #2 interaction(gear, am, drop = T)4.0 34.02157  2.781402  12.23181 1.599806e-12
    #3 interaction(gear, am, drop = T)4.1 37.94942  2.348132  16.16154 2.087857e-15
    #4 interaction(gear, am, drop = T)5.1 36.94589  3.096187  11.93271 2.822201e-12
    

    To get the table you want, you could do this:

    dtab <- table(mtcars$gear, mtcars$am)
    dtab[which(dtab != 0)] <- tidy(model)[grep("interaction", tidy(model)$term),]$estimate
    dtab[which(dtab == 0)] <- NA
      #       0        1
      #3 35.47755         
      #4 34.02157 37.94942
      #5          36.94589