【问题标题】:Fitted values from a different model in R来自 R 中不同模型的拟合值
【发布时间】:2018-09-21 20:54:34
【问题描述】:

我想知道是否可以计算与用于执行线性回归的子样本不同的观测样本的拟合值。特别是,我有一个包含 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


    【解决方案1】:

    您似乎想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))
    

    【讨论】:

    • 非常感谢!这比我期待的要容易得多。仍然是 R.. 的初学者。问题已解决。
    猜你喜欢
    • 2020-07-11
    • 2013-05-29
    • 1970-01-01
    • 2019-11-12
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    相关资源
    最近更新 更多