首页 > 解决方案 > 来自 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 中做到这一点?

谢谢你的帮助,马可

标签: 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))

推荐阅读