如何在 table 中呈现 R lm 对象交互系数?
How to present R lm object interaction coefficients in a table?
考虑具有交互项的 lm 拟合对象,例如:
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
是否有一种直接的方法来排列(仅)二维交互项的系数 table?例如:
gear am = 0 am = 1
3 35.478 NA
4 34.022 37.949
5 NA 36.946
您可以使用 broom
包轻松获取信息。这只是调整 table 以满足您的需要的问题:
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
要得到你想要的table,你可以这样做:
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