library(AER) data(CollegeDistance) # complete the function `TSLS()` TSLS <- function(Y, X, W = NULL, Z, data) { fs_model <- lm(as.formula(paste(..., collapse = "+"))), data = data) X_fitted <- ... ss_model <- lm(as.formula(paste(..., paste(..., collapse = "+"))), data = data) return(coefficients(...))} # use `TSLS()` to reproduce the estimates from Exercise 3 # complete the function `TSLS()` TSLS <- function(Y, X, W = NULL, Z, data) { # first stage regression & fitted values fs_model <- lm(as.formula(paste(X, "~", paste(c(Z, W), collapse = "+"))), data = data) X_fitted <- fs_model$fitted.values # second-stage regression ss_model <- lm(as.formula(paste(Y, "~", paste(W, collapse = "+"), "+ X_fitted")), data = data) # return coefficients of second stage return( coefficients(ss_model) )} # use `TSLS()` to reproduce the estimates from Exercise 3 TSLS(Y = "log(wage)", X = "education", Z = "distance", data = CollegeDistance) TSLS(Y = "log(wage)", X = "education", W = c("unemp", "ethnicity", "gender", "urban"), Z = "distance", data = CollegeDistance) ex() %>% check_fun_def("TSLS") %>% { check_arguments(.) check_call(., Y = "log(wage)", X = "education", Z = "distance", data = CollegeDistance) %>% check_result %>% check_equal } ex() %>% check_function("TSLS", index = 1) %>% { check_arg(., "Y") %>% check_equal() check_arg(., "X") %>% check_equal() check_arg(., "Z") %>% check_equal() } ex() %>% check_function("TSLS", index = 2) %>% { check_arg(., "Y") %>% check_equal() check_arg(., "X") %>% check_equal() check_arg(., "W") %>% check_equal() check_arg(., "Z") %>% check_equal() } success_msg("Nicely done!")