### Install ivDiag Development Version from GitHub Source: https://yiqingxu.org/packages/ivDiag/index.html Install the latest development version of the ivDiag package directly from GitHub using the remotes package. ```r library(remotes) install_github("apoorvalal/ivDiag") ``` -------------------------------- ### Install Required Packages for ivDiag Source: https://yiqingxu.org/packages/ivDiag/index.html This function checks for and installs all necessary packages for the ivDiag package if they are not already installed. It ensures all dependencies are met before using the package. ```r install_all <- function(packages) { installed_pkgs <- installed.packages()[, "Package"] for (pkg in packages) { if (!pkg %in% installed_pkgs) { install.packages(pkg) } } } packages <- c("foreach", "future", "doParallel", "lfe", "fixest", "ggplot2", "ggfortify", "wCorr", "haven", "glue", "patchwork", "testthat") install_all(packages) ``` -------------------------------- ### Perform ZFS Test with lm_robust Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html Conducts a ZFS (reduced-form) test using `lm_robust` on a subsample. This regression of the outcome on the instrument helps in setting up prior distributions for LTZ adjustments. Ensure `estimatr` library is installed. ```r library(estimatr) zfs <- lm_robust(totassoc_p ~ bishopcity + altitudine + escursione + costal + nearsea + population + pop2 + gini_land + gini_income + capoluogo, data = gsz_south, weights = gsz_south$population, se_type = "HC1") summary(zfs)$coefficients["bishopcity", 1:2] ``` -------------------------------- ### Install ivDiag from CRAN Source: https://yiqingxu.org/packages/ivDiag/index.html Use this command to install the stable version of the ivDiag package from CRAN. ```r install.packages("ivDiag", repos='http://cran.us.r-project.org') ``` -------------------------------- ### Check tF Output with testthat Source: https://yiqingxu.org/packages/ivDiag/reference/tF.html This snippet demonstrates how to use the 'testthat' package to verify the output of the `tF` function. It checks if the calculated t-ratio matches the expected value. ```r library(testthat) test_that("Check tF cF", { expect_equal(as.numeric(tf.out[2]), 1.96) }) ``` -------------------------------- ### Visualize First Stage (Raw Data) Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html Plots the raw data for the first stage of an IV analysis, showing the relationship between the instrument and the endogenous treatment. Requires setting up outcome, treatment, instrument, covariates, and cluster variables. ```R Y <- "e_vote_buying" # Y: outcome of interest D <-"lm_pob_mesa" # D: endogenous treatment Z <- "lz_pob_mesa_f" # Z: instrumental variable controls <- c("lpopulation", "lpotencial") # covariates of control variables cl <- "muni_code" # clusters # first stage (raw) par(mar = c(4, 4, 2, 2)) plot(rueda$lz_pob_mesa_f, rueda$lm_pob_mesa, col = "#777777", cex = 0.5, main = "Raw Data", xlab = "Instrument", ylab = "Treatment") abline(lm(lm_pob_mesa ~ lz_pob_mesa_f, data = rueda), col = 2, lwd = 2, lty = 2) ``` -------------------------------- ### Load ivDiag and datasets Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html Loads the ivDiag package and its associated datasets. Use ls() to view available datasets. ```R library(ivDiag) data(ivDiag) ls() #> [1] "gsz" "gsz_south" "rueda" ``` -------------------------------- ### tF() Source: https://yiqingxu.org/packages/ivDiag/reference/index.html Implements the Valid t-Ratio Procedure. ```APIDOC ## tF() ### Description Valid t-Ratio Procedure. ### Method Not applicable (R function) ### Endpoint Not applicable (R function) ### Parameters Not specified in source. ### Request Example Not applicable (R function) ### Response Not specified in source. ``` -------------------------------- ### ltz() Source: https://yiqingxu.org/packages/ivDiag/reference/index.html Performs the Local-to-Zero Test. ```APIDOC ## ltz() ### Description Local-to-Zero Test. ### Method Not applicable (R function) ### Endpoint Not applicable (R function) ### Parameters Not specified in source. ### Request Example Not applicable (R function) ### Response Not specified in source. ``` -------------------------------- ### Visualize First Stage (Partialled Out) Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html Plots the first stage of an IV analysis after partialling out covariates. This visualization helps to see the relationship between the residualized instrument and the residualized treatment. ```R # first stage (partial out) z_res <- lm(lz_pob_mesa_f ~ lpopulation + lpotencial, data = rueda)$residuals d_res <- lm(lm_pob_mesa ~ lpopulation + lpotencial, data = rueda)$residuals plot(z_res, d_res, col = "#777777", cex = 0.5, main = "Covariates Partialled Out", xlab = "Residualized Instrument", ylab = "Residualized Treatment") abline(lm(d_res ~ z_res), col = 2, lwd = 2, lty = 2) ``` -------------------------------- ### First-Stage Regression Results Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html Presents the results of the first-stage regression, including coefficients, standard errors (analytic and bootstrap), and p-values. Confidence intervals are based on the bootstrap percentile method. ```R g$est_fs #> Coef SE p.value SE.b CI.b2.5% CI.b97.5% p.value.b #> lz_pob_mesa_f 0.7957 0.0086 0 0.0087 0.7804 0.8145 0 ``` -------------------------------- ### Test ivDiag Output Source: https://yiqingxu.org/packages/ivDiag/reference/ivDiag.html This snippet demonstrates how to use the testthat package to assert specific values in the output of the ivDiag function, ensuring the estimation results are as expected. ```R library(testthat) test_that("Check ivDiag output", { expect_equal(as.numeric(g$est_2sls[1,1]), -0.9835) }) ``` -------------------------------- ### First-Stage F-Statistics Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html Reports various first-stage partial F-statistics to assess instrument strength, including standard, robust, cluster-robust, bootstrapped, and effective F statistics. ```R g$F_stat #> F.standard F.robust F.cluster F.bootstrap F.effective #> 3106.387 3108.591 8598.326 8408.152 8598.326 ``` -------------------------------- ### plot_ltz() Source: https://yiqingxu.org/packages/ivDiag/reference/index.html Visualizes Local-to-Zero Adjustment. ```APIDOC ## plot_ltz() ### Description Visualizing Local-to-Zero Adjustment. ### Method Not applicable (R function) ### Endpoint Not applicable (R function) ### Parameters Not specified in source. ### Request Example Not applicable (R function) ### Response Not specified in source. ``` -------------------------------- ### Tabulate Instrument and Treatment Variables in R Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html These R commands tabulate the counts for the instrument ('bishopcity') and the treatment ('libero_comune_allord') variables, providing a basic understanding of their distribution. ```r # table instrument and treatment table(gsz$bishopcity) #> #> 0 1 #> 5178 179 table(gsz$libero_comune_allord) #> #> 0 1 #> 5293 64 ``` -------------------------------- ### 2SLS Estimation and Inferential Results Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html Presents Two-Stage Least Squares (2SLS) estimation results using the `felm` package, including analytic and bootstrapped standard errors and confidence intervals. ```R g$est_2sls #> Coef SE t CI 2.5% CI 97.5% p.value #> Analytic -0.9835 0.1424 -6.9071 -1.2626 -0.7044 0 #> Boot.c -0.9835 0.1410 -6.9758 -1.2647 -0.7244 0 #> Boot.t -0.9835 0.1424 -6.9071 -1.2248 -0.7423 0 ``` -------------------------------- ### Check Local-to-Zero Adjustment Accuracy Source: https://yiqingxu.org/packages/ivDiag/reference/ltz.html This test verifies the accuracy of the Local-to-Zero adjustment by comparing the calculated coefficient to an expected value. It requires the `testthat` package and the output from the `ltz` function. ```R library(testthat) test_that("Check local-to-zero adjustment", { expect_equal(as.numeric(ltz_out$ltz[1]), 3.6088) }) ``` -------------------------------- ### Run IV Estimation and Diagnostics with ivDiag Source: https://yiqingxu.org/packages/ivDiag/reference/ivDiag.html Use this function to perform IV estimation and diagnostics. It requires a dataframe and variable names for the outcome, treatment, and instruments. Options for controls, fixed effects, clustering, and bootstrapping are available. ```R data(ivDiag) g <- ivDiag(data = rueda, Y = "e_vote_buying", D = "lm_pob_mesa", Z = "lz_pob_mesa_f", controls = c("lpopulation", "lpotencial"), cl = "muni_code", bootstrap = FALSE, run.AR = FALSE) plot_coef(g) ``` -------------------------------- ### Visualize LTZ Adjustment with Separate Inputs Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html Provides an alternative way to visualize LTZ adjustment results using `plot_ltz` by passing IV estimates, LTZ estimates, and prior information as separate two-element vectors. ```r plot_ltz(iv_est = ltz_out$iv[1:2], ltz_est = ltz_out$ltz[1:2], prior = ltz_out$prior) ``` -------------------------------- ### Disable Bootstrapping in ivDiag Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html Demonstrates how to disable the bootstrap option in the `ivDiag` function by setting `bootstrap = FALSE` for estimations that do not require bootstrapped standard errors. ```R ivDiag(data = rueda, Y=Y, D = D, Z = Z, controls = controls, cl = cl, bootstrap = FALSE) ``` -------------------------------- ### gsz Source: https://yiqingxu.org/packages/ivDiag/reference/index.html Dataset from GSZ (2016). ```APIDOC ## gsz ### Description Data from GSZ (2016). ### Method Not applicable (Dataset) ### Endpoint Not applicable (Dataset) ### Parameters Not specified in source. ### Request Example Not applicable (Dataset) ### Response Not specified in source. ``` -------------------------------- ### AR_test() Source: https://yiqingxu.org/packages/ivDiag/reference/index.html Performs the Anderson Rubin Test. ```APIDOC ## AR_test() ### Description Anderson Rubin Test. ### Method Not applicable (R function) ### Endpoint Not applicable (R function) ### Parameters Not specified in source. ### Request Example Not applicable (R function) ### Response Not specified in source. ``` -------------------------------- ### Check Anderson Rubin Test Results Source: https://yiqingxu.org/packages/ivDiag/reference/AR_test.html Verify the results of the Anderson Rubin test using expect_equal from the testthat package. This is useful for automated testing and ensuring reproducibility. ```R library(testthat) test_that("Check AR results", { expect_equal(as.numeric(AR.out$Fstat[1]), 50.5097) }) ``` -------------------------------- ### Run Omnibus Function in ivDiag Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html Initiates the `ivDiag` function for OLS and 2SLS estimation with multiple inferential methods. It outputs various diagnostic statistics and results. ```R library(ivDiag) g <- ivDiag(data = rueda, Y=Y, D = D, Z = Z, controls = controls, cl = cl) names(g) #> [1] "est_ols" "est_2sls" "AR" "F_stat" "rho" "tF" #> [7] "est_rf" "est_fs" "p_iv" "N" "N_cl" "df" #> [13] "nvalues" ``` -------------------------------- ### OLS Estimation and Inferential Results Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html Displays Ordinary Least Squares (OLS) estimation results, including analytic standard errors and bootstrap-based confidence intervals (coefficient and t-ratio methods). ```R g$est_ols #> Coef SE t CI 2.5% CI 97.5% p.value #> Analytic -0.675 0.1011 -6.6803 -0.8731 -0.4770 0 #> Boot.c -0.675 0.1030 -6.5548 -0.8923 -0.4891 0 #> Boot.t -0.675 0.1011 -6.6803 -0.8400 -0.5101 0 ``` -------------------------------- ### rueda Source: https://yiqingxu.org/packages/ivDiag/reference/index.html Dataset from Rueda (2017). ```APIDOC ## rueda ### Description Data from Rueda (2017). ### Method Not applicable (Dataset) ### Endpoint Not applicable (Dataset) ### Parameters Not specified in source. ### Request Example Not applicable (Dataset) ### Response Not specified in source. ``` -------------------------------- ### Reduced Form Regression Results Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html Displays results from the reduced form regression, similar to the first-stage regression output, including coefficients, standard errors, and confidence intervals. ```R g$est_rf #> Coef SE p.value SE.b CI.b2.5% CI.b97.5% p.value.b #> lz_pob_mesa_f -0.7826 0.1124 0 0.1118 -1.0127 -0.5731 0 ``` -------------------------------- ### Plot OLS and IV Coefficients Function Usage Source: https://yiqingxu.org/packages/ivDiag/reference/plot_coef.html This is the usage signature for the `plot_coef` function. It outlines the parameters available for customizing the visualization of OLS and IV coefficient estimates. ```R plot_coef(out, ols.methods = c("analy","bootc","boott"), iv.methods = c("analy","bootc","boott","ar","tf"), main = NULL, ylab = "Coefficient", grid = TRUE, stats = TRUE, ylim = NULL) ``` -------------------------------- ### tF Function Source: https://yiqingxu.org/packages/ivDiag/reference/tF.html Performs the valid t-ratio procedure. It takes the estimated coefficient, its standard error, and the first-stage F statistic as input to provide valid inference. ```APIDOC ## tF Performs the valid t-ratio procedure. ### Usage ```R tF(coef, se, Fstat, prec = 4) ``` ### Arguments * **coef** (numeric): a 2SLS coefficient. * **se** (numeric): a standard error estimate for the estimated 2SLS coefficient. * **Fstat** (numeric): a first-stage partial F statistic. * **prec** (numeric): precision of results (4 by default). ### Value Results from a valid t-ratio test given the first-stage F statistic. ### References Lee, David S, Justin McCrary, Marcelo J Moreira, and Jack Porter. 2022. "Valid t-Ratio Inference for IV." American Economic Review 112 (10): 3260–90. ### Examples ```R tf.out <- tF(coef = -0.9835, se = 0.1540, Fstat = 8598) library(testthat) test_that("Check tF cF", { expect_equal(as.numeric(tf.out[2]), 1.96) }) ``` ``` -------------------------------- ### gsz_south Source: https://yiqingxu.org/packages/ivDiag/reference/index.html Dataset from GSZ (2016): Subsample. ```APIDOC ## gsz_south ### Description Data from GSZ (2016): Subsample. ### Method Not applicable (Dataset) ### Endpoint Not applicable (Dataset) ### Parameters Not specified in source. ### Request Example Not applicable (Dataset) ### Response Not specified in source. ``` -------------------------------- ### IV Regression Summary Statistics Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html Provides key summary statistics for the IV regression, including the number of instruments (`p_iv`), total observations (`N`), number of clusters (`N_cl`), degrees of freedom (`df`), and unique values for outcome, treatment, and instruments (`nvalues`). ```R g$p_iv #> [1] 1 ``` ```R g$N #> [1] 4352 ``` ```R g$N_cl #> [1] 1098 ``` ```R g$df #> [1] 4348 ``` ```R g$nvalues #> e_vote_buying lm_pob_mesa lz_pob_mesa_f #> [1,] 16 4118 3860 ``` -------------------------------- ### ivDiag() Source: https://yiqingxu.org/packages/ivDiag/reference/index.html Omnibus Function for IV Estimation and Diagnostics. ```APIDOC ## ivDiag() ### Description Omnibus Function for IV Estimation and Diagnostics. ### Method Not applicable (R function) ### Endpoint Not applicable (R function) ### Parameters Not specified in source. ### Request Example Not applicable (R function) ### Response Not specified in source. ``` -------------------------------- ### plot_coef() Source: https://yiqingxu.org/packages/ivDiag/reference/index.html Plots OLS and IV Coefficients. ```APIDOC ## plot_coef() ### Description Plot OLS and IV Coefficents. ### Method Not applicable (R function) ### Endpoint Not applicable (R function) ### Parameters Not specified in source. ### Request Example Not applicable (R function) ### Response Not specified in source. ``` -------------------------------- ### Visualize LTZ Adjustment Results Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html Visualizes the sampling distribution of 2SLS estimates before and after LTZ adjustment, along with the prior distribution. The function `plot_ltz` takes the output from the `ltz` function. ```r plot_ltz(ltz_out, xlim = c(-0.5, 7)) ``` -------------------------------- ### Cross-Tabulate Instrument and Treatment in R Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html This R code generates a cross-tabulation of the instrument ('bishopcity') and the treatment ('libero_comune_allord') variables, showing their joint distribution. ```r table(gsz$bishopcity, gsz$libero_comune_allord) #> #> 0 1 #> 0 5173 5 #> 1 120 59 ``` -------------------------------- ### AR Test Results Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html Shows results from the Anderson-Rubin (AR) test, including the F-statistic, p-value, and confidence interval based on Chernozhukov and Hansen (2008). Indicates if the confidence interval is bounded. ```R g$AR #> $Fstat #> F df1 df2 p #> 48.4768 1.0000 4350.0000 0.0000 #> #> $ci.print #> [1] "[-1.2626, -0.7073]" #> #> $ci #> [1] -1.2626 -0.7073 #> #> $bounded #> [1] TRUE ``` -------------------------------- ### First-Stage Correlation Coefficient (rho) Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html Shows the Pearson correlation coefficient between the treatment variable and the predicted treatment from the first-stage regression, after partialling out covariates. ```R g$rho #> [1] 0.6455 ``` -------------------------------- ### Plot Coefficients and CIs Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html Generates a coefficient plot for OLS and 2SLS estimates with various inferential methods. The plot displays the effective F-statistic, number of observations, and clusters. Base R plotting functions can be used for further customization. ```r plot_coef(g) ``` ```r plot_coef(g, ols.methods = c("analy"), iv.methods = c("analy", "ar", "tf"), main = "Comparison between OLS and IV Estimates", ylab = "Estimates", grid = FALSE, stats = FALSE, ylim = c(-2, 0.5)) ``` -------------------------------- ### plot_coef Function Source: https://yiqingxu.org/packages/ivDiag/reference/plot_coef.html Visualizes point estimates and confidence intervals of OLS and IV estimates. It takes the output from `ivDiag::ivDiag` and allows customization of displayed methods, plot titles, labels, grid, statistics, and y-axis limits. ```APIDOC ## plot_coef ### Description Visualise point estimates and confidence intervals of OLS and IV estimates. ### Usage ```R plot_coef(out, ols.methods = c("analy","bootc","boott"), iv.methods = c("analy","bootc","boott","ar","tf"), main = NULL, ylab = "Coefficient", grid = TRUE, stats = TRUE, ylim = NULL) ``` ### Arguments * `out` (output from `ivDiag::ivDiag`): The primary input object containing the results from the `ivDiag` function. * `ols.methods` (vector of strings, optional): Specifies which inferential methods for OLS to display. Defaults to `c("analy","bootc","boott")`. * `iv.methods` (vector of strings, optional): Specifies which inferential methods for 2SLS to display. Defaults to `c("analy","bootc","boott","ar","tf")`. * `main` (string, optional): The title of the plot. * `ylab` (string, optional): The label for the y-axis. Defaults to "Coefficient". * `grid` (logical, optional): A flag to indicate whether to display grid lines. Defaults to `TRUE`. * `stats` (logical, optional): A flag to indicate whether to display statistics such as effective F, number of observations, and number of clusters. Defaults to `TRUE`. * `ylim` (two-element vector, optional): Specifies the range for the y-axis. ### Value A base R plot object. ``` -------------------------------- ### plot_ltz Function Source: https://yiqingxu.org/packages/ivDiag/reference/plot_ltz.html Visualise approximate sampling distributions for scalar IV coefficient with local-to-zero adjustment. ```APIDOC ## plot_ltz(out = NULL, iv_est = NULL, ltz_est = NULL, prior = NULL, xlim = NULL) ### Description Visualise approximate sampling distributions for scalar IV coefficient with local-to-zero adjustment. ### Arguments - **out** (output from `ivDiag::ltz`) - NULL - **iv_est** (a two-element vector of IV estimate and standard error) - NULL - **ltz_est** (a two-element vector of local-to-zero estimate and standard error) - NULL - **prior** (a two-element vector of prior mean and standard deviation) - NULL - **xlim** (a two-element vector specifying the range of the x-axis) - NULL ### Value A ggplot2 object. ``` -------------------------------- ### eff_F() Source: https://yiqingxu.org/packages/ivDiag/reference/index.html Calculates the Effective F statistic. ```APIDOC ## eff_F() ### Description Effective F statistic calculation. ### Method Not applicable (R function) ### Endpoint Not applicable (R function) ### Parameters Not specified in source. ### Request Example Not applicable (R function) ### Response Not specified in source. ``` -------------------------------- ### ltz Function Source: https://yiqingxu.org/packages/ivDiag/reference/ltz.html Estimates Local-to-Zero IV coefficients and SEs for a single instrument. ```APIDOC ## ltz ### Description Estimates Local-to-Zero IV coefficients and SEs for a single instrument. ### Usage ```R ltz(data, Y, D, Z, controls, FE = NULL, cl = NULL, weights = NULL, prior, prec = 4) ``` ### Arguments * `data` (dataframe): The name of the dataframe containing the data. * `Y` (string): The outcome variable. * `D` (string): The treatment variable. * `Z` (vector of strings): The instrumental variables. * `controls` (vector of strings): The control variables. * `FE` (vector of strings, optional): The fixed effects variables. * `cl` (string, optional): The clustering variable. * `weights` (string, optional): The variable that stores weights. * `prior` (numeric vector): Prior mean and standard deviation of the direct effect of instrument on outcome. * `prec` (numeric): Precision of results (defaults to 4). ### Value * `iv` (list): Results from a 2SLS regression. * `ltz` (list): Results after local-to-zero adjustment. * `prior` (list): Prior mean and standard deviation. ### Examples ```R data(ivDiag) controls <- c('altitudine', 'escursione', 'costal', 'nearsea', 'population', 'pop2', 'gini_land', 'gini_income') ltz_out <- ltz(data = gsz, Y = "totassoc_p", D = "libero_comune_allnord", Z = "bishopcity", controls = controls, weights = "population", prior = c(0.178, 0.137)) plot_ltz(ltz_out) library(testthat) test_that("Check local-to-zero adjustment", { expect_equal(as.numeric(ltz_out$ltz[1]), 3.6088) }) ``` ``` -------------------------------- ### Define IV Variables and Controls in R Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html This R code defines the outcome, treatment, instrument, and control variables for an IV analysis, consistent with the original paper's methodology. ```r Y <- "totassoc_p" D <- "libero_comune_allord" Z <- "bishopcity" weights <- "population" controls <- c('altitudine', 'escursione', 'costal', 'nearsea', 'population', 'pop2', 'gini_land', 'gini_income') ``` -------------------------------- ### Perform Valid t-Ratio Procedure Source: https://yiqingxu.org/packages/ivDiag/reference/tF.html Use this function to calculate valid t-ratios when performing instrumental variable analysis. Ensure you have the 2SLS coefficient, its standard error, and the first-stage F statistic. ```r tf.out <- tF(coef = -0.9835, se = 0.1540, Fstat = 8598) ``` -------------------------------- ### tF Procedure Results Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html Provides results from the tF procedure (Lee et al., 2022), including the critical value for the t-test adjusted by the effective F-statistic, and confidence intervals. ```R g$tF #> F cF Coef SE t CI2.5% CI97.5% p-value #> 8598.3264 1.9600 -0.9835 0.1424 -6.9071 -1.2626 -0.7044 0.0000 ``` -------------------------------- ### Estimate Local-to-Zero IV Coefficients Source: https://yiqingxu.org/packages/ivDiag/reference/ltz.html Use the `ltz` function to estimate Local-to-Zero Instrumental Variable coefficients and standard errors for a single instrument. Ensure the 'ivDiag' package is loaded and data is prepared. ```R data(ivDiag) controls <- c('altitudine', 'escursione', 'costal', 'nearsea', 'population', 'pop2', 'gini_land', 'gini_income') ltz_out <- ltz(data = gsz, Y = "totassoc_p", D = "libero_comune_allnord", Z = "bishopcity", controls = controls, weights = "population", prior = c(0.178, 0.137)) plot_ltz(ltz_out) ``` -------------------------------- ### Apply ivDiag and Plot Coefficients Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html Applies the `ivDiag` function to estimate OLS and 2SLS coefficients and plots the results. Ensure the necessary data and variables are correctly specified. ```r g <- ivDiag(data = gsz, Y = Y, D = D, Z = Z, controls = controls, weights = weights) g ``` ```r plot_coef(g) ``` -------------------------------- ### Perform tF Procedure Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html Applies the tF procedure for testing instrumental variables. This function requires the 2SLS coefficient, its standard error, and the first-stage F-statistic. It outputs various test statistics and p-values. ```r tF(coef = -0.9835, se = 0.1540, Fstat = 8598) ``` -------------------------------- ### Conduct AR Test Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html Performs the AR test, which is important for checking for endogeneity in instrumental variable models. The function returns the F-statistic, confidence intervals, and boundedness information. ```r AR_test(data = rueda, Y = Y, D = D, Z = Z, controls = controls, cl = cl, FE = NULL, weights = NULL) ``` -------------------------------- ### Perform Anderson Rubin Test Source: https://yiqingxu.org/packages/ivDiag/reference/AR_test.html Use AR_test to perform the Anderson Rubin test. Specify the data, outcome variable, treatment variable, instrumental variables, and control variables. Confidence interval calculation can be disabled. ```R data(ivDiag) AR.out <- AR_test(data = rueda, Y = "e_vote_buying", D = "lm_pob_mesa", Z = "lz_pob_mesa_f", controls = c("lpopulation", "lpotencial"), cl = "muni_code", CI = FALSE) ``` -------------------------------- ### Perform LTZ Adjustment Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html Applies the LTZ adjustment to IV estimates using a specified prior mean and standard deviation derived from a ZFS test. This function refines the 2SLS estimates by incorporating prior information. ```r ltz_out <- ltz(data = gsz, Y = Y, D = D, Z = Z, controls = controls, weights = weights, prior = c(0.178, 0.137)) ltz_out ``` -------------------------------- ### Compute Effective F Statistic Source: https://yiqingxu.org/packages/ivDiag/reference/eff_F.html Use this function to compute the effective F statistic. Ensure the data, outcome, treatment, and instrumental variables are correctly specified. Optional arguments include controls, fixed effects, clustering, and weights. ```R effF <- eff_F(data = rueda, Y = "e_vote_buying", D = "lm_pob_mesa", Z = "lz_pob_mesa_f", controls = c("lpopulation", "lpotencial"), cl = "muni_code") ``` ```R library(testthat) test_that("Check effective F", { expect_equal(floor(as.numeric(effF)), 8598) }) ``` -------------------------------- ### AR_test Function Source: https://yiqingxu.org/packages/ivDiag/reference/AR_test.html The AR_test function performs the Anderson Rubin test for instrumental variables, offering robustness to weak instruments. It takes a dataframe and specifies variables for the outcome, treatment, instruments, controls, and optional fixed effects, clustering, and weights. ```APIDOC ## AR_test Function ### Description Performs the Anderson Rubin test, which is robust to weak instruments. ### Usage ```R AR_test(data, Y, D, Z, controls, FE = NULL, cl = NULL, weights = NULL, prec = 4, CI = TRUE, alpha = 0.05, parallel = NULL, cores = NULL) ``` ### Arguments * **data** (dataframe): The name of the dataframe containing the data. * **Y** (string): The name of the outcome variable. * **D** (string): The name of the treatment variable. * **Z** (vector of strings): The names of the instrumental variables. * **controls** (vector of strings): The names of the control variables. * **FE** (vector of strings, optional): The names of the fixed effects variables. * **cl** (string, optional): The name of the clustering variable. * **weights** (string, optional): The name of the variable that stores weights. * **prec** (numeric): Precision of results (default is 4). * **CI** (logical): A flag controlling whether to calculate the confidence interval using the inversion method (default is TRUE). * **alpha** (numeric): The level of statistical significance (default is 0.05). * **parallel** (logical, optional): A flag controlling parallel computing. * **cores** (numeric, optional): Setting the number of cores for parallel computing. ### Value * **Fstat** (numeric): The F statistic, degrees of freedom, and p-value. * **ci.print** (numeric): The confidence interval calculated via inversion (printed version). * **ci** (numeric): The confidence interval calculated via inversion (numeric version). * **bounded** (logical): Indicates if the confidence interval is bounded. ### Examples ```R data(ivDiag) AR.out <- AR_test(data = rueda, Y = "e_vote_buying", D = "lm_pob_mesa", Z = "lz_pob_mesa_f", controls = c("lpopulation", "lpotencial"), cl = "muni_code", CI = FALSE) library(testthat) test_that("Check AR results", { expect_equal(as.numeric(AR.out$Fstat[1]), 50.5097) }) ``` ``` -------------------------------- ### ivDiag Function Source: https://yiqingxu.org/packages/ivDiag/reference/ivDiag.html Conducts various estimation and diagnostic procedures for instrumental variable designs. ```APIDOC ## ivDiag Function ### Description Conducts various estimation and diagnostic procedures for instrumental variable designs in one shot. ### Usage ```R ivDiag(data, Y, D, Z, controls = NULL, FE = NULL, cl = NULL, weights = NULL, bootstrap = TRUE, run.AR = TRUE, nboots = 1000, parallel = TRUE, cores = NULL, seed = 94305, prec = 4, debug = FALSE) ``` ### Arguments * **data** (dataframe): Name of a dataframe. * **Y** (string): A string indicating the outcome variable. * **D** (string): A string indicating the treatment variable. * **Z** (vector of strings): A vector of strings indicating the instrumental variables. * **controls** (vector of strings, optional): A vector of strings indicating the control variables. * **FE** (vector of strings, optional): A vector of strings indicating the fixed effects variables. * **cl** (string, optional): A string indicating the clustering variable. * **weights** (string, optional): A string indicating the variable that stores weights. * **bootstrap** (boolean): Whether to turn on bootstrap (TRUE by default). * **run.AR** (boolean): Whether to run AR test (TRUE by default). * **nboots** (numeric): A numeric value indicating the number of bootstrap runs. * **parallel** (logical): A logical flag controlling parallel computing. * **cores** (numeric, optional): Setting the number of cores. * **seed** (numeric): Setting seed. * **prec** (numeric): Precision of CI in string (4 by default). * **debug** (boolean): For debugging purposes. ### Value * **est_ols** (results): Results from an OLS regression. * **est_2sls** (results): Results from a 2SLS regression. * **AR** (results): Results from an Anderson-Rubin test. * **F_stat** (results): Various F statistics. * **rho** (numeric): Pearson correlation coefficient between the treatment and predicted treatment from the first stage regression (all covariates are partialled out). * **tF** (results): Results from the tF procedure based on Lee et al. (2022). * **est_rf** (results): Results from the first stage regression. * **est_fs** (results): Results from the reduced form regression. * **p_iv** (numeric): The number of instruments. * **N** (numeric): The number of observations. * **N_cl** (numeric): The number of clusters. * **df** (numeric): The degree of freedom left from the 2SLS regression. * **nvalues** (list): The unique values the outcome Y, the treatment D, and each instrument in Z in the 2SLS regression. ### Examples ```R data(ivDiag) g <- ivDiag(data = rueda, Y = "e_vote_buying", D = "lm_pob_mesa", Z = "lz_pob_mesa_f", controls = c("lpopulation", "lpotencial"), cl = "muni_code", bootstrap = FALSE, run.AR = FALSE) plot_coef(g) library(testthat) test_that("Check ivDiag output", { expect_equal(as.numeric(g$est_2sls[1,1]), -0.9835) }) ``` ``` -------------------------------- ### Conduct Effective F-statistic Test Source: https://yiqingxu.org/packages/ivDiag/articles/iv_tutorial.html Calculates the effective F-statistic for instrumental variable regression. This test is crucial for assessing the strength of instruments. Ensure the correct data and variable names are provided. ```r eff_F(data = rueda, Y = Y, D = D, Z = Z, controls = controls, cl = cl, FE = NULL, weights = NULL) ``` -------------------------------- ### eff_F Function Source: https://yiqingxu.org/packages/ivDiag/reference/eff_F.html Computes the effective F statistic. This function is used to diagnose potential issues with weak instruments in instrumental variable regression. ```APIDOC ## eff_F Function ### Description Computes the effective F statistic. ### Usage ```R eff_F(data, Y, D, Z, controls = NULL, FE = NULL, cl = NULL, weights = NULL, prec = 4) ``` ### Arguments * `data` (dataframe): The name of the dataframe containing the data. * `Y` (string): The name of the outcome variable. * `D` (string): The name of the treatment variable. * `Z` (vector of strings): The names of the instrumental variables. * `controls` (vector of strings, optional): The names of the control variables. * `FE` (vector of strings, optional): The names of the fixed effects variables. * `cl` (string, optional): The name of the clustering variable. * `weights` (string, optional): The name of the variable that stores weights. * `prec` (numeric): The precision of the results (defaults to 4). ### Value Returns the effective F statistic. ### See Also `ivDiag` ### References Olea, José Luis Montiel, and Carolin Pflueger. 2013. "A Robust Test for Weak Instruments." Journal of Business & Economic Statistics 31 (3): 358–69. ### Examples ```R # Example usage of eff_F effF <- eff_F(data = rueda, Y = "e_vote_buying", D = "lm_pob_mesa", Z = "lz_pob_mesa_f", controls = c("lpopulation", "lpotencial"), cl = "muni_code") # Test the result library(testthat) test_that("Check effective F", { expect_equal(floor(as.numeric(effF)), 8598) }) ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.