基于拟合线性模型估算数据

impute data based on fitted linear model

我正在查看来自 this kaggle competition 的数据。我关注这两列:

这里 LotFrontage 有缺失值,而 LotArea 没有。这两个变量非常相关。所以我想我适合线性回归模型并使用拟合模型估算 LotFrontage 的缺失值。这是我的尝试(我是 R newby):

ggplot(OriginalData, aes(x = LotArea, y = LotFrontage)) + geom_point()

fit <- lm(LotFrontage ~ LotArea, OriginalData)
tidy(fit)

Slope <- coef(fit)[term = 'LotArea']
Intercept <- coef(fit)[term = '(Intercept)']

OriginalData$LotFrontage[is.na(OriginalData$LotFrontage)] <- Intercept + (Slope * OriginalData$LotArea)

sum(is.na(OriginalData$LotFrontage))
ggplot(OriginalData, aes(x = LotArea, y = LotFrontage)) + geom_point()

我觉得有些地方不太对劲。只是想知道,如何使用拟合的斜率和截距在散点图中绘制一条简单的线?谢谢!

首先,你在填补缺失值的过程中犯了一个错误。

Data$Y[is.na(Data$Y)] <- Intercept + (Slope * Data$X)

<-符号前后的值长度不同。 它会导致警告。

您应该修改为:

Data$Y[is.na(Data$Y)] <- (Intercept + (Slope * Data$X))[is.na(Data$Y)]

如果你想添加一个简单的回归线,你可以使用:

  • (1) geom_abline( )

+ geom_abline(slope = Slope, intercept = Intercept)

但这是在你有斜率和截距的情况下。

geom_abline()只能做一条直线。(简单线性回归)

  • (2) geom_smooth( )

+ geom_smooth(method = "lm")

它使用平滑方法来拟合数据,例如。 lm,glm,gam,黄土,MASS::rlm。 您可以搜索帮助页面以获取详细信息。