6-R语言最小二乘法实战

6-R语言最小二乘法实战

其实R 包ivreg已经提供了方法进行最小二乘法(2SLS),不过为了了解整个R 的操作过程,这里我还是使用最基本的lm 进行二次拟合,实现整个过程。

6.1-准备与获得数据

这里我使用ivreg 中的数据集:

my_packages<- c("ggplot2", "tidyverse", 
                "RColorBrewer", "paletteer", "ivreg")
tmp <- sapply(my_packages, function(x) library(x, character.only = T)); rm(tmp, my_packages)
data("SchoolingReturns", package = "ivreg")
my_data <- SchoolingReturns[, 1:8]
glimpse(my_data)

Rows: 3,010
Columns: 8
$ wage        <dbl> 548, 481, 721, 250, 729, 500, 565, 608…
$ education   <dbl> 7, 12, 12, 11, 12, 12, 18, 14, 12, 12,…
$ experience  <dbl> 16, 9, 16, 10, 16, 8, 9, 9, 10, 11, 13…
$ ethnicity   <fct> afam, other, other, other, other, othe…
$ smsa        <fct> yes, yes, yes, yes, yes, yes, yes, yes…
$ south       <fct> no, no, no, no, no, no, no, no, no, no…
$ age         <dbl> 29, 27, 34, 27, 34, 26, 33, 29, 28, 29…
$ nearcollege <fct> no, no, no, yes, yes, yes, yes, yes, y…

6.2-两次回归找拟合值

首先是第一阶段,通过工具变量,对暴露因素求回归:

接下来获得每一项的预测值:

利用第一阶段的预测值结果,进行第二阶段回归分析:

6.3-ivreg包实现

不难发现,ivreg 的拟合结果,实际上就是我们6.2 步骤里计算的结果:

除此之外,你可能还会注意到ivreg 的summary 结果中,默认配置了三种Diagnostic tests,下面会进行简单介绍。

Last updated