Is there any way to fit a `glm()` so that all levels are included (i.e. no reference level)?

大兔子大兔子 提交于 2019-12-30 05:30:09

问题


Consider the code:

x <- read.table("http://data.princeton.edu/wws509/datasets/cuse.dat",
                header=TRUE)[,1:2]

fit <- glm(education ~ age, family="binomial", data=x)

summary(fit)

Where age has 4 levels: "<25" "25-29" "30-39" "40-49"

The results are:

So by default, one of the levels is used as a reference level. Is there a way to have glm output coefficients for all 4 levels + the intercept (i.e. have no reference level)? Software packages like SAS do this by default, so I was wondering if there was any option for this.

Thanks!


回答1:


See ?formula, specifically, the meaning of including + 0 in your model specification...

# Sample data - explanatory variable (continuous)
x <- runif( 100 )
# explanatory data, factor with 3 levels
f <- as.factor( sample( 3 , 100 , TRUE ) )
# outcome data
y <- runif( 100 ) + rnorm(100) + rnorm( 100 , mean = c(1,3,6) )

# model without intercept
summary( glm( y ~ x + f + 0 ) )
#Call:
#glm(formula = y ~ x + f + 0)

#Deviance Residuals: 
#    Min       1Q   Median       3Q      Max  
#-5.7316  -1.8923   0.0195   1.8918   5.9520  

#Coefficients:
#   Estimate Std. Error t value Pr(>|t|)    
#x    0.3216     0.9772   0.329    0.743    
#f1   3.4493     0.6823   5.055 2.06e-06 ***
#f2   3.6349     0.6959   5.223 1.02e-06 ***
#f3   3.1962     0.6598   4.844 4.87e-06 ***



回答2:


You'll want to use the model.matrix function to convert the factors in the age variable to binary variables.

See this answer.

EDIT: Here is an example:

x <- read.table("http://data.princeton.edu/wws509/datasets/cuse.dat",
                header=TRUE)[,1:2]
binary_variables <- model.matrix(~ x$age -1, x)
fit <- glm(x$education ~ binary_variables, family="binomial")
summary(fit)


来源:https://stackoverflow.com/questions/23347467/is-there-any-way-to-fit-a-glm-so-that-all-levels-are-included-i-e-no-refer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!