从R中的coef函数创建系数矩阵

时间:2014-04-11 12:02:36

标签: r extract glm

从这段代码:

    treatment     <- factor(rep(c(1, 2), c(43, 41)), 
                        levels = c(1, 2),
                        labels = c("placebo", "treated"))
improved      <- factor(rep(c(1, 2, 3, 1, 2, 3), c(29, 7, 7, 13, 7, 21)),
                        levels = c(1, 2, 3),
                        labels = c("none", "some", "marked"))    
numberofdrugs <- rpois(84, 10) + 1    
healthvalue   <- rpois(84, 5)   
y             <- data.frame(healthvalue, numberofdrugs, treatment, improved)
test          <- glm(healthvalue~numberofdrugs+treatment+improved + treatment:improved, y, family=poisson)
summary(test)

我们使用coef()函数得到以下内容:

> coef(test)
                    (Intercept)                   numberofdrugs                treatmenttreated 
                    1.549172817                     0.004261529                     0.014634807 
                   improvedsome                  improvedmarked   treatmenttreated:improvedsome 
                    0.201150827                    -0.129251907                    -0.258841251 
treatmenttreated:improvedmarked 
                    0.051326071 

我希望将变量的系数排列成矢量,将相互作用的系数排列成矩阵,以便能够更容易地使用它们。

例如:

coef.intercept=(1.5491)

coef.numberofdrugs=(0.00426)

coef.treatment=(0, 0.01463)

coef.improved=(0, 0.2011, -0.1292)

和相关矩阵,将处理作为行并改进为列,如下所示:

coef.correlation =

(0       0       0  )

(0  -0.2588  -0.2588)

有没有有效的方法可以做到这一点?

请注意,coef()函数中未列出的任何系数都应设置为零,并且我缩短了上面的一些数字。

1 个答案:

答案 0 :(得分:1)

我相信allEffects包中的effects可能会引起关注:

library(effects)
allEffects(test)
 model: healthvalue ~ numberofdrugs + treatment + improved + treatment:improved

 numberofdrugs effect
numberofdrugs
       6        8       10       12       14       16       18       20 
4.050962 4.322559 4.612365 4.921601 5.251570 5.603662 5.979360 6.380247 

 treatment*improved effect
         improved
treatment     none     some   marked
  placebo 4.416773 3.713517 5.461153
  treated 4.596433 4.902746 5.309627