r语言 - 修改逻辑回归中因子的名称

  • 本文关键字:回归 r语言 修改 r rename
  • 更新时间 :
  • 英文 :


让我先举一个示例数据。

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)

当我输入summary(model1)时,我得到

 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

现在请忽略模型估计,因为数据是假
的R中有没有办法更改出现在最左侧列上的估计值的名称,使它们看起来更清晰?例如,删除as.factor,并在因子水平之前放置一个_。输出应如下所示:

                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

除了上面的注释之外,另一部分是将所有数据放在数据框中,并相应地命名变量。然后,变量名称不会取自塞进公式中的丑陋大表达式:

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

对于第一部分,在拟合模型之前,请先获取正确的数据。收集数据框中的变量,并将处理后的变量包含在该数据框中,这样您就可以控制它们的名称。例如:

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)
dat <- data.frame(y = y, x1 = x1, x2 = factor(x2),
                  x1.gt.0 = factor(x1 >= 0))
model1 <- glm(y~ x1.gt.0 + x2, data = dat, family = binomial)
> coef(model1)
(Intercept) x1.gt.0TRUE       x2Old     x2Young 
 -0.1835144   0.7469661   0.7469661  18.0026168

这就是您应该在大多数 R 函数中使用公式接口的方式。

最新更新