我编了一个例子来说明我的问题。想象一下,我有一个数据集,我用伽马分布的残差训练一个广义线性模型。
library(MASS)
df <- read.csv('test.csv')
model <- glm(formula = y ~ method * site + year + 0,
family=Gamma(link = "log"), data = df)
我得到的东西是这样的。
> summary(model)
Coefficients:
Estimate Std. Error t value Pr(>|t|)
methodM0 3.89533 0.13670 28.496 < 2e-16 ***
methodM1 5.63965 0.20940 26.933 < 2e-16 ***
methodM2 -55.854107 73.982453 -0.755 0.450
methodM3 -55.731730 73.986509 -0.753 0.451
siteS1 -0.002872 0.098226 -0.029 0.977
siteS2 0.060892 0.107795 0.565 0.572
siteS3 -0.016239 0.102258 -0.159 0.874
year 0.030813 0.036743 0.839 0.402
methodM1:siteS1 -0.030616 0.144592 -0.212 0.832
methodM2:siteS1 -0.030632 0.144663 -0.212 0.832
methodM3:siteS1 0.064179 0.145593 0.441 0.659
methodM1:siteS2 -0.146505 0.152012 -0.964 0.335
methodM2:siteS2 -0.039610 0.148024 -0.268 0.789
methodM3:siteS2 -0.202881 0.150406 -1.349 0.178
methodM1:siteS3 NA NA NA NA
methodM2:siteS3 0.081617 0.144040 0.567 0.571
methodM3:siteS3 -0.064155 0.147771 -0.434 0.664
这张表是虚构数字的结果 但重点是M1方法和S3站点之间的交互作用导致了 NA
. 我如何设置GLM不计算该特定的交互作用,在训练后删除该交互作用,或者将模型中的NA值设置为 0
?
@jared_mamrot给出的答案指向了 此相关问题 这是很相似的。
s <- source("http://pastebin.com/raw.php?i=EcMEVqUC")$value
lm(income ~ age + cit * prof, data=s)
这里 lm
而非 glm
是遵循的,但我发现,当我运行相关问题的公认答案时,更新似乎都没有解决这个例子。
model1 <- lm(income ~ age + cit * prof, data=s)
model2 <- update(model1, . ~ . - citforeign:profofficial)
从 model1
我们有
> model1
Call:
lm(formula = income ~ age + cit * prof, data = s)
Coefficients:
(Intercept) age citwest citforeign
2205.231 -3.825 74.871 30.066
profblue-collar profofficial citwest:profblue-collar citforeign:profblue-collar
-189.146 -147.332 27.792 -60.223
citwest:profofficial citforeign:profofficial
-122.220 NA
再看 model2
一脉相承
> model1
Call:
lm(formula = income ~ age + cit * prof, data = s)
Coefficients:
(Intercept) age citwest citforeign
2205.231 -3.825 74.871 30.066
profblue-collar profofficial citwest:profblue-collar citforeign:profblue-collar
-189.146 -147.332 27.792 -60.223
citwest:profofficial citforeign:profofficial
-122.220 NA
如你所见。update
似乎并不能消除 NA
.
你可以用 update
? 如:?
model1 <- glm(formula = y ~ method * site + year + 0,
family=Gamma(link = "log"), data = df)
model2 <- update(model1, . ~ . - methodM1:siteS3)
(每 从估算中删除一些因素相互作用的条款。 https:/www.r-bloggers.comusing-the-update-function-during-variable-selection)
编辑
下面是一个使用 update
的例子数据上的方法。从估算中删除一些因素相互作用的条款。
s <- source("http://pastebin.com/raw.php?i=EcMEVqUC")$value
model1 <- glm(income ~ age + cit * prof, data=s)
model2 <- update(model1, . ~ . - cit:prof)
summary_glm(model1)
summary_glm(model2)
编辑2
如果你不想使用更新,你可以尝试放弃交互(见下文),但我不知道这将如何影响模型的有效性或是否可取。
s <- source("http://pastebin.com/raw.php?i=EcMEVqUC")$value
model1 <- glm(income ~ age + cit * prof, data=s)
model2 <- glm(income ~ model.matrix(model1)[,1:9], data=s)
summary_glm(model1)
summary_glm(model2)