简体   繁体   中英

R: Using the predict function to add standard error and confidence intervals to predictions

I've made this model:

model <- lm(mpg ~ wt, mtcars)

I now want to made prediction for new data, and I can do this with the effects package

library(effects)
effect_df <- as.data.frame(effect(c("wt"), model, list(wt = 1:5)))
effect_df 

  wt      fit        se    lower    upper
1  1 31.94065 1.3515519 29.18042 34.70089
2  2 26.59618 0.8678067 24.82389 28.36848
3  3 21.25171 0.5519713 20.12444 22.37899
4  4 15.90724 0.6938618 14.49018 17.32429
5  5 10.56277 1.1328743  8.24913 12.87641

I can made the same predictions with expand.grid like this:

expand_grid_df <- expand.grid(wt  = 1:5)
expand_grid_df$fit <- predict(model, expand_grid_df)
expand_grid_df

  wt      fit
1  1 31.94065
2  2 26.59618
3  3 21.25171
4  4 15.90724
5  5 10.56277

How can I add columns for the standard error and upper/lower confidence intervals for fit to expand_grid_df , as in effect_df ?

This will do it:

expand_grid_df <- expand.grid(wt  = 1:5)
expand_grid_df$fit <- predict(model, expand_grid_df, se.fit=TRUE, interval="confidence")$fit
expand_grid_df$se.fit <- predict(model, expand_grid_df, se.fit=TRUE)$se.fit
expand_grid_df

  wt  fit.fit  fit.lwr  fit.upr    se.fit
1  1 31.94065 29.18042 34.70089 1.3515519
2  2 26.59618 24.82389 28.36848 0.8678067
3  3 21.25171 20.12444 22.37899 0.5519713
4  4 15.90724 14.49018 17.32429 0.6938618
5  5 10.56277  8.24913 12.87641 1.1328743

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM