Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying the names of factors in logistic regression

Tags:

r

rename

Let me start by presenting an example data.

set.seed(1)
x1=rnorm(10)
y=as.factor(sample(c(1,0),10,replace=TRUE))
x2=sample(c('Young','Middle','Old'),10,replace=TRUE)
model1 <- glm(y~as.factor(x1>=0)+as.factor(x2),binomial)

When I enter summary(model1), I get

 Estimate Std. Error z value Pr(>|z|)
(Intercept)              -0.1835     1.0926  -0.168    0.867
as.factor(x1 >= 0)TRUE    0.7470     1.7287   0.432    0.666
as.factor(x2)Old          0.7470     1.7287   0.432    0.666
as.factor(x2)Young       18.0026  4612.2023   0.004    0.997

Please ignore the model estimates as such now since the data is fake
Is there a way in R to change the names of the estimates appearing on the leftmost column so that they look clearer? E.g. removing the as.factor, and putting an_ before the factor level. The output should be as follows:

                Estimate Std. Error z value Pr(>|z|)
(Intercept)      -0.1835     1.0926  -0.168    0.867
(x1 >= 0)_TRUE    0.7470     1.7287   0.432    0.666
(x2)_Old          0.7470     1.7287   0.432    0.666
(x2)_Young       18.0026  4612.2023   0.004    0.997
like image 685
Stat-R Avatar asked May 01 '12 19:05

Stat-R


1 Answers

In addition to the comments above, the other piece is to place all your data in a data frame, and name the variables accordingly. Then the variable names aren't taken from a big ugly expression crammed into your formula:

library(car)
dat <- data.frame(y = y,
                  x1 = cut(x1,breaks = c(-Inf,0,Inf),labels = c("x1 < 0","x1 >= 0"),right = FALSE),
                  x2 = as.factor(x2))

#To illustrate Brian's suggestion above
options(decorate.contr.Treatment = "")
model1 <- glm(y~x1+x2,binomial,data = dat,
            contrasts = list(x1 = "contr.Treatment",x2 = "contr.Treatment"))
summary(model1)

Call:
glm(formula = y ~ x1 + x2, family = binomial, data = dat, contrasts = list(x1 = "contr.Treatment", 
    x2 = "contr.Treatment"))

Deviance Residuals: 
    Min       1Q   Median       3Q      Max  
-1.7602  -0.8254   0.3456   0.8848   1.2563  

Coefficients:
             Estimate Std. Error z value Pr(>|z|)
(Intercept)   -0.1835     1.0926  -0.168    0.867
x1[x1 >= 0]    0.7470     1.7287   0.432    0.666
x2[Old]        0.7470     1.7287   0.432    0.666
x2[Young]     18.0026  4612.2023   0.004    0.997
like image 191
joran Avatar answered Nov 26 '22 12:11

joran