r - 来自 R 中不同模型的拟合值
问题描述
我想知道是否可以计算与用于执行线性回归的子样本不同的观测样本的拟合值。特别是,我有一个包含 400 个人的完整数据框。我想执行两个单独的 OLS 回归,根据虚拟值对数据帧进行二次采样。
ols1<-lm(log_consumption ~ log_wage + Age + Age2 + Education, data=df, subset = type==1)
ols2<-lm(log_consumption ~ log_wage + Age + Age2 + Education, data=df, subset = type==0)
这段代码显然返回了两个单独的模型和相应的拟合值。但是,我想首先根据模型 1,然后根据模型 2 获取我所有数据框的拟合值(即所有 400 个人的拟合值)。基本上我想比较整个数据框的拟合值,利用我在两种不同的“制度”下得到的 OLS 系数之间的差异。
有没有办法在 R 中做到这一点?
谢谢你的帮助,马可
解决方案
看起来你想要predict()
。尝试:predict(ols1, df)
和predict(ols2, df)
。这是使用 iris 数据集的示例。
## data
df <- iris
df$type <- rep(c(0, 1), 75) # 75 type 0 and 75 type 1
## models
ols1 <- lm(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width,
data = df, subset = type == 1)
ols2 <- lm(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width,
data = df, subset = type == 0)
## predicted values for all the 150 observations
# just for checking: fitted(ols1) and fitted(ols2) give the 75 fitted values
length(fitted(ols1))
length(fitted(ols2))
# here, we want predicted values instead of fitted values
# the the predict() function, we can obtained predicted values for all the 150 observations
predict(ols1, df)
predict(ols2, df)
# check: we have 150 observations
length(predict(ols1, df))
length(predict(ols2, df))
推荐阅读
- firebase - 我无法在一台设备上安装重复的颤振应用程序
- ios - JTAppleCalendar - 仅针对可见单元格的单元格自动布局更新存在问题
- python - tensorflow 1.12 版本是否有 Keras 调谐器?如果不是,有什么替代方案?
- performance - 在 datadog 中跟踪 .Net 核心 API
- javascript - Vue3动态创建组件
- c++ - Visual Studio 2010 停止实施对可执行文件的更改
- angular - 如何将 C# .net 代码转换为 Angular 9
- docker - 如何退出在 Docker 容器中运行的命令?
- ios - iOS 停止在 Performance Core 上运行我的代码
- google-sheets - 如何在电子表格中为图像创建数组公式