Write a function in R that implements a two-stage least squares (2SLS) estimator. The input of the function should be the dependent variable y, the endogenous predictor x, and the instrumental variable(s) z. The output of the function only needs to include the point estimate of the coefficient on x.
(a) Copy and paste your code below.
(b) Load the AER package in R and show that your function produces the same results as the ivreg function (you only need to show the equivalence of the point estimates).
(c) Suppose you could not observe z, but instead observed another instrument z' that is generated as follows. zprime = z + rnorm(n, sd=10) Is z' still a valid instrument? Provide evidence using your data.
(d) Rerun the IV regression (with ivreg) using z' instead of z. What is the effect on your inference for β1?