I would like to get the upper and lower limits of the confidence interval for each observation in loess function to replicate what ggplot
does in the geom_smooth()
我想获得黄土函数中每个观测值的置信区间的上限和下限,以复制ggplot在geom_smooth()中的作用
library(ggplot2)
ggplot(mtcars, aes(x = mpg, y = hp)) +
geom_point() +
geom_smooth(method = 'loess')
I know I can get the upper and lower bounds from linear models, but this is not available for loess:
我知道我可以从线性模型得到上限和下限,但这不适用于黄土:
lm_mod <- lm(hp ~ mpg, mtcars)
predict(lm_mod, mtcars, interval="confidence", level=0.95)
loess_mod <- loess(hp ~ mpg, mtcars)
predict(loess_mod, mtcars, interval="confidence", level=0.95)
1 个解决方案
#1
3
Figured it out! The confidence intervals can be calculated from the standard errors which can be added prediction object using the se = TRUE
argument. 1.96 standard deviations equates to a 95% confidence interval (with a normal distribution and hence assuming normality in the errors).
弄清楚了!可以从标准误差计算置信区间,该标准误差可以使用se = TRUE参数添加预测对象。 1.96标准差等于95%置信区间(具有正态分布,因此假设误差正常)。
loess_mod <- loess(hp ~ mpg, mtcars)
pred <- predict(loess_mod, mtcars, se=TRUE)
mtcars1$lwl <- pred$fit-1.96*pred$se.fit
mtcars1$upl <- pred$fit+1.96*pred$se.fit
library(ggplot2)
ggplot(mtcars1, aes(x = mpg, y = hp)) +
geom_point() +
geom_smooth(method = 'loess') +
geom_line(aes(y = lwl), color = "red") +
geom_line(aes(y = upl), color = "red")
Hope this helps someone else.
希望这有助于其他人。
#1
3
Figured it out! The confidence intervals can be calculated from the standard errors which can be added prediction object using the se = TRUE
argument. 1.96 standard deviations equates to a 95% confidence interval (with a normal distribution and hence assuming normality in the errors).
弄清楚了!可以从标准误差计算置信区间,该标准误差可以使用se = TRUE参数添加预测对象。 1.96标准差等于95%置信区间(具有正态分布,因此假设误差正常)。
loess_mod <- loess(hp ~ mpg, mtcars)
pred <- predict(loess_mod, mtcars, se=TRUE)
mtcars1$lwl <- pred$fit-1.96*pred$se.fit
mtcars1$upl <- pred$fit+1.96*pred$se.fit
library(ggplot2)
ggplot(mtcars1, aes(x = mpg, y = hp)) +
geom_point() +
geom_smooth(method = 'loess') +
geom_line(aes(y = lwl), color = "red") +
geom_line(aes(y = upl), color = "red")
Hope this helps someone else.
希望这有助于其他人。