簡體   English   中英

R:使用預測功能將標准誤差和置信區間添加到預測中

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

我做了這個模型:

model <- lm(mpg ~ wt, mtcars)

現在,我要對新數據進行預測,可以使用effects包來進行預測

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

我可以像這樣用expand.grid做出相同的預測:

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

如何添加列的標准誤差和上/下的置信區間為fitexpand_grid_df ,如effect_df

可以做到這一點:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM