如何在表中呈现R lm对象交互系数?

时间:2015-04-23 22:19:23

标签: r lm interaction

考虑具有交互术语的lm fit对象,例如:

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  

是否有一种直接的方法来安排(仅)二维表中的交互项的系数?例如:

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

1 个答案:

答案 0 :(得分:1)

您可以使用broom包轻松获取信息。只需调整满足您需求的表格即可:

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

要获得所需的表格,您可以这样做:

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