感谢您提供您的数据集(我希望该链接永远有效,以便每个人都可以访问)。我将其读入数据框train
.
使用debug_contr_error
, debug_contr_error2
and NA_preproc
提供的辅助函数如何调试“对比只能应用于具有 2 个或更多级别的因素”错误? https://stackoverflow.com/q/44200195/4891738,我们就可以轻松分析问题了。
info <- debug_contr_error2(log_SalePrice ~ ., train)
## the data frame that is actually used by `lm`
dat <- info$mf
## number of cases in your dataset
nrow(train)
#[1] 1460
## number of complete cases used by `lm`
nrow(dat)
#[1] 1112
## number of levels for all factor variables in `dat`
info$nlevels
# MSZoning Street Alley LotShape LandContour
# 4 2 3 4 4
# Utilities LotConfig LandSlope Neighborhood Condition1
# 1 5 3 25 9
# Condition2 BldgType HouseStyle RoofStyle RoofMatl
# 6 5 8 5 7
# Exterior1st Exterior2nd MasVnrType ExterQual ExterCond
# 14 16 4 4 4
# Foundation BsmtQual BsmtCond BsmtExposure BsmtFinType1
# 6 5 5 5 7
# BsmtFinType2 Heating HeatingQC CentralAir Electrical
# 7 5 5 2 5
# KitchenQual Functional FireplaceQu GarageType GarageFinish
# 4 6 6 6 3
# GarageQual GarageCond PavedDrive PoolQC Fence
# 5 5 3 4 5
# MiscFeature SaleType SaleCondition MiscVal_bool MoYrSold
# 4 9 6 2 55
如你看到的,Utilities
是这里的违规变量,因为它只有 1 个级别。
因为你有很多字符/因子变量train
,我想知道你是否有NA
对于他们来说。如果我们添加NA
作为一个有效的水平,我们可能会得到更完整的案例。
new_train <- NA_preproc(train)
new_info <- debug_contr_error2(log_SalePrice ~ ., new_train)
new_dat <- new_info$mf
nrow(new_dat)
#[1] 1121
new_info$nlevels
# MSZoning Street Alley LotShape LandContour
# 5 2 3 4 4
# Utilities LotConfig LandSlope Neighborhood Condition1
# 1 5 3 25 9
# Condition2 BldgType HouseStyle RoofStyle RoofMatl
# 6 5 8 5 7
# Exterior1st Exterior2nd MasVnrType ExterQual ExterCond
# 14 16 4 4 4
# Foundation BsmtQual BsmtCond BsmtExposure BsmtFinType1
# 6 5 5 5 7
# BsmtFinType2 Heating HeatingQC CentralAir Electrical
# 7 5 5 2 6
# KitchenQual Functional FireplaceQu GarageType GarageFinish
# 4 6 6 6 3
# GarageQual GarageCond PavedDrive PoolQC Fence
# 5 5 3 4 5
# MiscFeature SaleType SaleCondition MiscVal_bool MoYrSold
# 4 9 6 2 55
我们确实得到了更完整的案例,但是Utilities
还是有一级的。这意味着大多数不完整的案例实际上是由NA
在您的数值变量中,我们无能为力(除非您有统计上有效的方法来估算这些缺失值)。
由于您只有一个单水平因子变量,因此与中给出的方法相同当“对比只能应用于具有 2 个或更多级别的因素”时,如何进行 GLM? https://stackoverflow.com/q/50297260/4891738将工作。
new_dat$Utilities <- 1
simplelm <- lm(log_SalePrice ~ 0 + ., data = new_dat)
该模型现在已成功运行。然而,它是等级不足 https://stackoverflow.com/q/37090722/4891738。您可能想要采取一些措施来解决这个问题,但保持原样就可以了。
b <- coef(simplelm)
length(b)
#[1] 301
sum(is.na(b))
#[1] 9
simplelm$rank
#[1] 292