我已经制作了这个模型:
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
如何为fit
expand_grid_df
添加标准错误和上/下置信区间的列,如effect_df
?
答案 0 :(得分:2)
这样做:
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