如何将二进制值保存在因子变量中?

How to keep binary values in a Factor Variable?

我正在执行玩具示例逻辑回归。 我想做的是:保持因子变量 a_fac 作为二进制变量.

这是我的代码:

set.seed(8)
a = rbinom( n = 10, size = 1, prob = 0.5)
d = seq(1:length(a))

a_fac = factor(a, labels=c("class1", "class2"))
plot(d, a_fac)

##Logistic Regression
lr = glm(a_fac~d, family=binomial(link="logit"))       ##cannot perform the log regression with factor var.
lr = glm(a~d, family=binomial(link="logit"))

##plotting
plot(d,a_fac, main = "logistic regression",  ylim = c(0,2))
lines(d,lr$fitted.values)

##this is the correct plot i want to obtain with the factor variable
plot(d,a, main = "logistic regression")
lines(d,lr$fitted.values)

我可以这样做还是必须保留同一变量的对象?谢谢

我想您需要将 factor 转换为 numeric 以实现 glm,即

glm(as.numeric(a_fac)-1~d)

这样

> glm(as.numeric(a_fac)-1~d)

Call:  glm(formula = as.numeric(a_fac) - 1 ~ d)

Coefficients:
(Intercept)            d  
    0.13333      0.08485  

Degrees of Freedom: 9 Total (i.e. Null);  8 Residual
Null Deviance:      2.4 
Residual Deviance: 1.806    AIC: 17.26

您的第一个 glm 模型不是逻辑回归,因为您没有包含 family 参数并指定 "binomial"。

lr = glm(a_fac~d) # Error!

错误是由于 R 试图对非数字结果进行线性回归。正确的命令应该是:

lr = glm(a_fac~d, family=binomial(link="logit"))

对于绘图,因子被视为第一级以 1 开头的整数。因此,如果您想对 y 轴使用 0 和 1,但要附加标签,请使用结果向量的 a 版本,抑制刻度标签 (yaxt="n"),然后添加一个带有您自己的标签的轴。

plot(d, a, main = "logistic regression", yaxt="n", ylab="Outcome")
lines(d, lr2$fitted.values, col="red")
axis(side=2, at=c(0,1), labels=levels(a_fac), las=1)