gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:04:41 25 4
gpt4 key购买 nike

让我首先展示一个示例数据。

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

关于r - 修改逻辑回归中的因子名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10403104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com