【发布时间】:2014-04-29 04:37:15
【问题描述】:
在 R(使用 glm)中运行回归分析时,由于数据“缺失”,案例被删除。有没有办法标记哪些案例已被删除?理想情况下,我想从我的原始数据框中删除这些。
非常感谢
【问题讨论】:
标签: r regression glm
在 R(使用 glm)中运行回归分析时,由于数据“缺失”,案例被删除。有没有办法标记哪些案例已被删除?理想情况下,我想从我的原始数据框中删除这些。
非常感谢
【问题讨论】:
标签: r regression glm
glm() 返回的模型拟合对象记录了由于不完整而被排除的数据的行号。它们有点被埋没了,但你可以这样取回它们:
## Example data.frame with some missing data
df <- mtcars[1:6, 1:5]
df[cbind(1:5,1:5)] <- NA
df
# mpg cyl disp hp drat
# Mazda RX4 NA 6 160 110 3.90
# Mazda RX4 Wag 21.0 NA 160 110 3.90
# Datsun 710 22.8 4 NA 93 3.85
# Hornet 4 Drive 21.4 6 258 NA 3.08
# Hornet Sportabout 18.7 8 360 175 NA
# Valiant 18.1 6 225 105 2.76
## Fit an example model, and learn which rows it excluded
f <- glm(mpg~drat,weight=disp, data=df)
as.numeric(na.action(f))
# [1] 1 3 5
或者,要获得行索引而不必拟合模型,请使用与 model.frame() 的输出相同的策略:
as.numeric(na.action(model.frame(mpg~drat,weight=disp, data=df)))
# [1] 1 3 5
【讨论】:
as.numeric(f$na.action) 而不是as.numeric(attr(f$model, "na.action"))?
as.numeric(na.action(f)) 也可以。我刚刚编辑了答案以合并该信息。谢谢!
如果没有可重现的示例,我无法提供针对您的问题量身定制的代码,但这里有一个应该可以工作的通用方法。假设您的数据框称为df,您的变量称为y、x1、x2 等。假设您的模型中需要y、x1、x3 和x6。
# Make a vector of the variables that you want to include in your glm model
# (Be sure to include any weighting or subsetting variables as well, per Josh's comment)
glm.vars = c("y","x1","x3","x6")
# Create a new data frame that includes only those rows with no missing values
# for the variables that are in your model
df.glm = df[complete.cases(df[ , glm.vars]), ]
另外,如果您只想查看至少有一个缺失值的行,请执行以下操作(注意添加 !(“not”运算符)):
df[!complete.cases(df[ , glm.vars]), ]
【讨论】:
glm() 的调用使用其weights 或subset 参数,请确保包含传递给glm.vars 中的变量。