R GLM函数省略数据

标签 r logistic-regression na missing-data glm

我正在创建一个逻辑回归模型来预测因子二元结果变量(是/否),但遇到了丢失数据的奇怪问题。基本上,与让 GLM 执行自己的 na.action 相比,当我在运行 GLM 函数之前手动过滤模型中的观察结果时,我会得到非常不同的 R 平方。请参阅下面的示例代码:

outcome <- rnorm(100)
outcome <- ifelse(outcome <= 0.5, 0, 1)
var1 <- rnorm(100)
var2 <- rnorm(100)
var3 <- c(rnorm(88), NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA)
df <- data.frame(cbind(outcome, var1, var2, var3))
df$outcome <- factor(df$outcome)

model_1 <- glm(outcome ~., data = df, family = "binomial")
nagelkerke(model_1)

模型_1的结果:

$Pseudo.R.squared.for.model.vs.null
                             Pseudo.R.squared
McFadden                             0.160916
Cox and Snell (ML)                   0.192093
Nagelkerke (Cragg and Uhler)         0.261581

现在我尝试预先过滤掉这些案例并收到完全不同的 R 平方:

df_clean <- filter(df, is.na(var3) == FALSE)

model_2 <- glm(outcome ~., data = df_clean, family = "binomial")
nagelkerke(model_2)

模型_2的结果:

$Pseudo.R.squared.for.model.vs.null
                             Pseudo.R.squared
McFadden                            0.0110171
Cox and Snell (ML)                  0.0123142
Nagelkerke (Cragg and Uhler)        0.0182368

考虑到 GLM 的默认 na.action = na.omit (我将其解释为省略具有缺失值的情况),为什么会出现这种情况?这本质上不是和预先过滤掉这些情况然后运行模型是一样的吗?

此外,我尝试将 na.action 更改为“na.omit”和“na.exclude”并收到相同的输出。感谢您的帮助!

最佳答案

您是正确的,na.omit 将省略缺失值并运行您的模型。事实上,当您运行 summary(model_1)summary(model_2) 时,您应该会看到相同的输出。

但是,当原始数据集中的一个变量中存在 NA 值时,您使用的 nagelkerke 函数会遇到问题。从那里documentation ...

The fitted model and the null model should be properly nested. That is, the terms of one need to be a subset of the the other, and they should have the same set of observations. One issue arises when there are NA values in one variable but not another, and observations with NA are removed in the model fitting. The result may be fitted and null models with different sets of observations. Setting restrictNobs to TRUE ensures that only observations in the fit model are used in the null model. This appears to work for lm and some glm models, but causes the function to fail for other model object types

如果将 restrictNobs 设置为 TRUE,您应该会看到相同的输出

关于R GLM函数省略数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60104332/

相关文章:

r - 如何根据列组前缀替换列组的空白?

r - 如何在 r 中获取 coplot 的图例?

r - 有没有另一种方法可以在 worker 中加载额外的包(并行计算)?

r - 将平均线添加到 ggplot

python - scikit-learn - 类型错误 : fit() missing 1 required positional argument: 'y'

r - 有没有办法对不同长度的变量进行 wilcoxon 检验?

r - 使用 rCharts 的 dimple.js 中的线标记

machine-learning - 机器学习中的逻辑回归

machine-learning - Scikit_learn 的 PolynomialFeatures 与逻辑回归导致分数较低

删除数据框中的非数字值(*未知*)