<?xml version="1.0" encoding="UTF-8"?>
<rss  xmlns:atom="http://www.w3.org/2005/Atom" 
      xmlns:media="http://search.yahoo.com/mrss/" 
      xmlns:content="http://purl.org/rss/1.0/modules/content/" 
      xmlns:dc="http://purl.org/dc/elements/1.1/" 
      version="2.0">
<channel>
<title>Yanghao Wang</title>
<link>https://yanghaowang.github.io/blog.html</link>
<atom:link href="https://yanghaowang.github.io/blog.xml" rel="self" type="application/rss+xml"/>
<description>Practical tutorials and methodological deep dives into A/B testing, causal inference, SQL, and Python from the perspective of an applied economist.</description>
<generator>quarto-1.9.38</generator>
<lastBuildDate>Mon, 20 Mar 2023 06:56:27 GMT</lastBuildDate>
<item>
  <title>Process Missing Data in Python</title>
  <link>https://yanghaowang.github.io/posts/python-missing-data/</link>
  <description><![CDATA[ 






<p><img src="https://yanghaowang.github.io/posts/python-missing-data/missingdata.jpg" class="img-fluid"></p>
<section id="detect-missing-values" class="level2">
<h2 class="anchored" data-anchor-id="detect-missing-values">Detect Missing Values</h2>
<p>Missing data can be filled with values like <code>'NA'</code>, <code>'NaN'</code>, <code>'-'</code>, or <code>'.'</code> etc. To detect these values, we can</p>
<ol type="1">
<li>use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.unique.html"><code>pandas.Series.unique()</code></a> to find unique values and then check the first and the last element from the sorted list of unique values by <a href="https://numpy.org/doc/stable/reference/generated/numpy.sort.html"><code>numpy.sort()</code></a>;</li>
<li>use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.info.html"><code>pandas.DataFrame.info()</code></a> to check if there are default missing values, <code>'NA'</code>s or <code>'NaN'</code>s, in a pandas DataFrame by columns; &gt; check numeric variables further if they are reported as <code>object</code> with no missing values since a numeric variable will be treated as an <code>object</code> (a string variable) if numeric values are mixed with <code>'NA'</code>s or <code>'NaN'</code>s</li>
<li>use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.describe.html"><code>pandas.DataFrame.describe()</code></a> to check descriptive statistics of variables and their counts of non-missing values</li>
</ol>
<p>Once missing values have been identified, we can reload data using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html"><code>pandas.read_csv()</code></a> with specified <code>na_value</code> argument.</p>
<p>We can either fill missing values by imputation or delete them using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html"><code>pandas.DataFrame.dropna()</code></a>.</p>
</section>
<section id="detect-types-of-missing" class="level2">
<h2 class="anchored" data-anchor-id="detect-types-of-missing">Detect Types of Missing</h2>
<p>Reference: <a href="https://en.wikipedia.org/wiki/Missing_data#Types">https://en.wikipedia.org/wiki/Missing_data#Types</a></p>
<ul>
<li><p>Missing Completely at Random (MCAR)</p></li>
<li><p>Missing at Random (MAR)</p>
<blockquote class="blockquote">
<p>There is a systematic relationship between missing value and other observed data, but not the variable itself. Since MAR is an assumption that is <em>impossible</em> to verify statistically, we must rely on its substantive reasonableness. <strong>Wikipedia Example</strong>: Males are less likely to fill in a depression survey but this has nothing to do with their level of depression, after accounting for maleness.</p>
</blockquote></li>
<li><p>Missing not at Random (MNAR)</p>
<blockquote class="blockquote">
<p>To extend the previous example, this would occur if men failed to fill in a depression survey because of their level of depression. This also raises another concern of <a href="https://en.wikipedia.org/wiki/Selection_bias"><em>selection bias</em></a>.</p>
</blockquote></li>
</ul>
<p><code>missingno.heatmap()</code>, <code>missingno.dendrogram()</code>, and <code>missingno.matrix()</code> in Python package <a href="https://github.com/ResidentMario/missingno"><code>missingno</code></a> can help us visualize the patterns of missing values.</p>
</section>
<section id="impute-values" class="level2">
<h2 class="anchored" data-anchor-id="impute-values">Impute Values</h2>
<ul>
<li><p>Impute with mean, median, mode, and a constant using <a href="https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html"><code>sklearn.impute.SimpleImputer()</code></a> with specified <code>strategy</code> argument.</p></li>
<li><p>Impute with lead or lag values in a <em>time-series</em> data frame using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html"><code>pandas.DataFrame.fillna()</code></a> with specified <code>method</code> (<code>='bfill', 'ffill'</code> and etc.) argument or <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.interpolate.html"><code>pandas.DataFrame.interpolate()</code></a> with specified <code>method</code> (<code>='linear', 'nearest', 'quadratic'</code> and etc.) argument.</p></li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Set nrows to 3 and ncols to 1</span></span>
<span id="cb1-2">fig, axes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>))</span>
<span id="cb1-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Create a dictionary of interpolated DataFrames for looping </span></span>
<span id="cb1-4">interpolations <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Linear Interpolation'</span>: linear, </span>
<span id="cb1-5">                    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Quadratic Interpolation'</span>: quadratic, </span>
<span id="cb1-6">                    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Nearest Interpolation'</span>: nearest}</span>
<span id="cb1-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Loop over axes and interpolations</span></span>
<span id="cb1-8"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> ax, df_key <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">zip</span>(axes, interpolations):</span>
<span id="cb1-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Select and also set the title for a DataFrame</span></span>
<span id="cb1-10">    interpolations[df_key].Ozone.plot(color<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'red'</span>, marker<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'o'</span>, linestyle<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'dotted'</span>, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax)</span>
<span id="cb1-11">    airquality.Ozone.plot(title<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>df_key <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">' - Ozone'</span>, marker<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'o'</span>, ax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ax)</span>
<span id="cb1-12">plt.show()</span></code></pre></div></div>
<ul>
<li><p>Impute with advanced models</p>
<p>References: <a href="https://scikit-learn.org/stable/modules/impute.html">https://scikit-learn.org/stable/modules/impute.html</a> and</p>
<p><a href="https://github.com/iskandr/fancyimpute">https://github.com/iskandr/fancyimpute</a></p>
<ul>
<li><p>Nearest neighbors (KNN) imputation</p>
<blockquote class="blockquote">
<p>When imputing missing values for a categorical variable, we firstly transform the categorical variable to a numerical variable using <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OrdinalEncoder.html"><code>OrdinalEncoder().fit_transform(X)</code></a>, then apply the imputation method, and lastly transform the imputed encoded variable back to the categorical using <code>OrdinalEncoder().inverse_transform(X)</code>.</p>
</blockquote></li>
<li><p>Multivariate feature imputation</p>
<blockquote class="blockquote">
<p>This method iteratively estimates a regression of every feature with missing values on other features, and uses regression predicts for imputation. It is very robust. However, we should keep an eye on the concern of information leakage if the dependent/target variable (or the dependent/target-related variables) of the final model is (are) used in the imputation.</p>
</blockquote></li>
</ul></li>
</ul>
<p><strong>Takeaway</strong>: The best imputation solution might vary by data sets. We can select the solution by comparing the final model performance using data sets processed by different imputation methods.</p>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Python</category>
  <category>Missing Data</category>
  <guid>https://yanghaowang.github.io/posts/python-missing-data/</guid>
  <pubDate>Mon, 20 Mar 2023 06:56:27 GMT</pubDate>
</item>
<item>
  <title>Compare An Unknown with A Known Distribution</title>
  <link>https://yanghaowang.github.io/posts/compare-distributions/</link>
  <description><![CDATA[ 






<p><img title="" src="https://upload.wikimedia.org/wikipedia/commons/4/47/Archimedes_bath.jpg" alt="" width="413" data-align="center"></p>
<p>How to detect a distribution for a set of data points? When it comes to this question, we don’t spend a second creating a histogram or a density plot to visualize the distribution of the given data points. If there are some potential distributions to be compared, we can add their PDF curves to the existing plot or create a QQ plot. That is it. We then move forward.</p>
<p>I didn’t think of this question carefully until I failed an interview. Unfortunately, after saying we could detect the distribution by visualizing a density plot, I was expected to propose a test statistic. I vaguely remembered the rationale of the Kolmogorov-Smirnov (KS) Test but forgot the name. Although I found the KS statistic after the interview, I was still wondering if there was another simple test. My Eureka moment appeared when I watched a YouTube video about the Chi-squared Test. Yes, we can also compare the distributions from two sets of data points using the Chi-squared Test.</p>
<section id="data-simulation" class="level2">
<h2 class="anchored" data-anchor-id="data-simulation">Data Simulation</h2>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Load packages</span></span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(data.table) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># data manipulation</span></span>
<span id="cb1-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(ggplot2)    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># data visualization</span></span>
<span id="cb1-4"></span>
<span id="cb1-5"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20221119</span>)</span>
<span id="cb1-6">n <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100000</span></span>
<span id="cb1-7">df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.table</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'id'</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n,</span>
<span id="cb1-8">                 <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'beta'</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbeta</span>(n, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">shape1 =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">shape2 =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>),</span>
<span id="cb1-9">                 <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'normal'</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sd =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>),</span>
<span id="cb1-10">                 <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'normal_wide'</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sd =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>),</span>
<span id="cb1-11">                 <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'unif'</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">runif</span>(n, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">min =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">max =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>),</span>
<span id="cb1-12">                 <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'unif_shift'</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">runif</span>(n, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">min =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">max =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.2</span>),</span>
<span id="cb1-13">                 <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'test'</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">runif</span>(n, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">min =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">max =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb1-14">df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">melt</span>(df, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">id.vars =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'id'</span>, </span>
<span id="cb1-15">           <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">measure.vars =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'beta'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'normal'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'normal_wide'</span>,</span>
<span id="cb1-16">                            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'unif'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'unif_shift'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'test'</span>),</span>
<span id="cb1-17">           <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">variable.name =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'dist'</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">value.name =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'val'</span>)</span>
<span id="cb1-18">df[, quant<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">=</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cut</span>(val, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">breaks=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>)), by<span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'dist'</span>]</span>
<span id="cb1-19"></span>
<span id="cb1-20"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> val, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">color =</span> dist)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb1-21">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_density</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_x_continuous</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n.breaks=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span></code></pre></div></div>
<p><img src="https://yanghaowang.github.io/posts/compare-distributions/sample_dist.png" class="img-fluid"></p>
</section>
<section id="q-q-plot" class="level2">
<h2 class="anchored" data-anchor-id="q-q-plot">Q-Q Plot</h2>
<p>“In statistics, a&nbsp;<strong>Q–Q plot</strong>&nbsp;(<strong>quantile-quantile plot</strong>) is a probability plot, a&nbsp;<a href="https://en.wikipedia.org/wiki/List_of_graphical_methods" title="List of graphical methods">graphical method</a>&nbsp;for comparing two&nbsp;probability distributions&nbsp;by plotting their&nbsp;<em>quantiles</em> against each other. A point&nbsp;(<em>x</em>,&nbsp;<em>y</em>)&nbsp;on the plot corresponds to one of the quantiles of the second distribution (<em>y</em>-coordinate) plotted against the same quantile of the first distribution (<em>x</em>-coordinate).” – <a href="https://en.wikipedia.org/wiki/Q%E2%80%93Q_plot">Wikipedia</a></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qqplot</span>(df[dist<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'beta'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>val, df[dist<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'test'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>val, </span>
<span id="cb2-2">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xlab =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"beta"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ylab =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"test"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">main =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Q-Q Plot"</span>)</span>
<span id="cb2-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">a=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">b=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">col=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'red'</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lwd=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<p><img src="https://yanghaowang.github.io/posts/compare-distributions/QQ_beta.png" class="img-fluid"></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qqplot</span>(df[dist<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'normal'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>val, df[dist<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'test'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>val, </span>
<span id="cb3-2">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xlab =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"normal"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ylab =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"test"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">main =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Q-Q Plot"</span>)</span>
<span id="cb3-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">a=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">b=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">col=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'red'</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lwd=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<p><img src="https://yanghaowang.github.io/posts/compare-distributions/QQ_normal.png" class="img-fluid"></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qqplot</span>(df[dist<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'normal'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>val, df[dist<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'normal_wide'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>val, </span>
<span id="cb4-2">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xlab =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"normal"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ylab =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"normal_wide"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">main =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Q-Q Plot"</span>)</span>
<span id="cb4-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">a=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">b=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">col=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'red'</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lwd=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<p><img src="https://yanghaowang.github.io/posts/compare-distributions/QQ_normal2.png" class="img-fluid"></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qqplot</span>(df[dist<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'unif_shift'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>val, df[dist<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'test'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>val, </span>
<span id="cb5-2">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xlab =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"unif_shift"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ylab =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"test"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">main =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Q-Q Plot"</span>)</span>
<span id="cb5-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">a=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">b=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">col=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'red'</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lwd=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<p><img src="https://yanghaowang.github.io/posts/compare-distributions/QQ_unif2.png" class="img-fluid"></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qqplot</span>(df[dist<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'unif'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>val, df[dist<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'test'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>val, </span>
<span id="cb6-2">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xlab =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"unif"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ylab =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"test"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">main =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Q-Q Plot"</span>)</span>
<span id="cb6-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">a=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">b=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">col=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'red'</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lwd=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<p><img src="https://yanghaowang.github.io/posts/compare-distributions/QQ_unif.png" class="img-fluid"></p>
<ul>
<li><p>If two distributions are similar, the points in the Q–Q plot will approximately lie on the identity line <img src="https://latex.codecogs.com/png.latex?y=x"></p></li>
<li><p>If two distributions are similar, the points in the Q–Q plot will approximately lie on a line, parallel to the identity line</p></li>
<li><p>A Q-Q plot also sheds light on the shift of location parameters (e.g., how the median point in the test set locates in the point set from a known distribution) and the change in scale parameters (e.g., how the standard deviation of the test set differs from that of the standard normal)</p></li>
</ul>
</section>
<section id="kolmogorovsmirnov-test" class="level2">
<h2 class="anchored" data-anchor-id="kolmogorovsmirnov-test">Kolmogorov–Smirnov Test</h2>
<p>“In&nbsp;statistics, the&nbsp;<strong>Kolmogorov–Smirnov test</strong>&nbsp;(<strong>K–S test</strong>&nbsp;or&nbsp;<strong>KS test</strong>) is a&nbsp;<a href="https://en.wikipedia.org/wiki/Nonparametric_statistics">nonparametric test</a>&nbsp;of the equality of continuous, <em>one-dimensional</em>&nbsp;probability distributions that can be used to compare a&nbsp;sample with a reference probability distribution (one-sample K–S test) or to compare two samples (two-sample K–S test).” – <a href="https://en.wikipedia.org/wiki/Kolmogorov%E2%80%93Smirnov_test">Wikipedia</a></p>
<p>The Kolmogorov–Smirnov test may also be used to test whether two underlying one-dimensional probability distributions differ.</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AD_%7Bn,m%7D=%5Csup_x%5Cleft%7CF_%7B1,n%7D(x)%20-%20F_%7B2,m%7D(x)%5Cright%7C%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?F_%7B1,n%7D"> and <img src="https://latex.codecogs.com/png.latex?F_%7B2,m%7D"> are the empirical distribution functions of the first and the second sample respectively.</p>
<p><img src="https://yanghaowang.github.io/posts/compare-distributions/KS_Test.png" class="img-fluid"></p>
<blockquote class="blockquote">
<p>Illustration of the two-sample Kolmogorov–Smirnov statistic. Red and blue lines each correspond to an empirical distribution function, and the black arrow is the two-sample KS statistic.</p>
</blockquote>
<p>For large samples, the null hypothesis is rejected at level <img src="https://latex.codecogs.com/png.latex?%5Calpha"> if</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AD_%7Bn,m%7D%3Ec(%5Calpha)%5Csqrt%7B%5Cfrac%7Bn+m%7D%7Bn%5Ccdot%20m%7D%7D,%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?n"> and <img src="https://latex.codecogs.com/png.latex?m"> are the sizes of the first and the second sample respectively. The value of <img src="https://latex.codecogs.com/png.latex?c(%5Calpha)"> is given in the table below:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th style="text-align: left;"><img src="https://latex.codecogs.com/png.latex?%5Calpha"></th>
<th style="text-align: center;">0.20</th>
<th style="text-align: center;">0.10</th>
<th style="text-align: center;">0.05</th>
<th style="text-align: center;">0.025</th>
<th style="text-align: center;">0.01</th>
<th style="text-align: center;">0.005</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: left;"><img src="https://latex.codecogs.com/png.latex?c(%5Calpha)"></td>
<td style="text-align: center;">1.073</td>
<td style="text-align: center;">1.224</td>
<td style="text-align: center;">1.358</td>
<td style="text-align: center;">1.48</td>
<td style="text-align: center;">1.628</td>
<td style="text-align: center;">1.731</td>
</tr>
</tbody>
</table>
<p>and in general</p>
<p><img src="https://latex.codecogs.com/png.latex?%0Ac(%5Calpha)=%5Csqrt%7B-%5Cln%5Cleft(%5Cfrac%7B%5Calpha%7D%7B2%7D%5Cright)%5Ctimes%5Cfrac%7B1%7D%7B2%7D%7D.%0A"></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ks.test</span>(df[dist<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'normal'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>val, df[dist<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'normal_wide'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>val)</span></code></pre></div></div>
<pre><code>##  Two-sample Kolmogorov-Smirnov test
## 
## data:  df[dist == "normal"]$val and df[dist == "normal_wide"]$val
## D = 0.16634, p-value &lt; 2.2e-16
## alternative hypothesis: two-sided</code></pre>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ks.test</span>(df[dist<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'beta'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>val, df[dist<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'test'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>val)</span></code></pre></div></div>
<pre><code>##  Two-sample Kolmogorov-Smirnov test
## 
## data:  df[dist == "beta"]$val and df[dist == "test"]$val
## D = 0.10644, p-value &lt; 2.2e-16
## alternative hypothesis: two-sided</code></pre>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb11-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ks.test</span>(df[dist<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'unif_shift'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>val, df[dist<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'test'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>val)</span></code></pre></div></div>
<pre><code>##  Two-sample Kolmogorov-Smirnov test
## 
## data:  df[dist == "unif_shift"]$val and df[dist == "test"]$val
## D = 0.20304, p-value &lt; 2.2e-16
## alternative hypothesis: two-sided</code></pre>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb13-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ks.test</span>(df[dist<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'unif'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>val, df[dist<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'test'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>val)</span></code></pre></div></div>
<pre><code>##  Two-sample Kolmogorov-Smirnov test
## 
## data:  df[dist == "unif"]$val and df[dist == "test"]$val
## D = 0.00356, p-value = 0.5506
## alternative hypothesis: two-sided</code></pre>
</section>
<section id="chi-squared-test" class="level2">
<h2 class="anchored" data-anchor-id="chi-squared-test">Chi-squared Test</h2>
<p>Suppose there are&nbsp;<img src="https://latex.codecogs.com/png.latex?n">&nbsp;observations, classified into&nbsp;<img src="https://latex.codecogs.com/png.latex?k">&nbsp;mutually exclusive groups with a respective number&nbsp;<img src="https://latex.codecogs.com/png.latex?x_i">&nbsp;(for <img src="https://latex.codecogs.com/png.latex?i=1,2,%5Cdots,k">) of observations in the <img src="https://latex.codecogs.com/png.latex?i">th group. In the null hypothesis, we assume an observation falls into the&nbsp;<img src="https://latex.codecogs.com/png.latex?i">th group with a probability&nbsp;of <img src="https://latex.codecogs.com/png.latex?p_i">, such that</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Csum_%7Bi=1%7D%5E%7Bk%7Dp_i=1%20%5Ctext%7B%20and%20%7D%0A%5Csum_%7Bi=1%7D%5Ek%20m_i=%5Csum_%7Bi=1%7D%5Ek%20(n%5Ctimes%20p_i)=%20n.%0A"></p>
<p>As <img src="https://latex.codecogs.com/png.latex?n%5Crightarrow%5Cinfty">, the limiting distribution of the quantity given below is the <img src="https://latex.codecogs.com/png.latex?%5Cchi%5E2"> distribution with <img src="https://latex.codecogs.com/png.latex?k-1"> degrees of freedom:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AX%5E2=%5Csum_%7Bi=1%7D%5Ek%5Cfrac%7B(x_i-m_i)%5E2%7D%7Bm_i%7D=%5Csum_%7Bi=1%7D%5Ek%5Cfrac%7Bx_i%5E2%7D%7Bm_i%7D-n%0A"></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb15-1">df_test <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dcast</span>(df, quant <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> dist, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">value.var =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'val'</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fun.aggregate =</span> length)</span>
<span id="cb15-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(df_test)</span></code></pre></div></div>
<pre><code>##    quant beta normal normal_wide unif unif_shift test
## 1:     1 9001      2           1 1963       1918 1987
## 2:     2 3884      4           2 1931       1984 1955
## 3:     3 2891      5           2 2041       1993 2019
## 4:     4 2459      9           2 1991       1995 2009
## 5:     5 2213     21           6 2001       1965 1941
## 6:     6 2028     29          13 2065       2049 1985</code></pre>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb17-1">df_cut <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> df[, .(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cut_min =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(val)), by<span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'dist'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'quant'</span>)][<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">order</span>(dist, quant)]</span>
<span id="cb17-2">quant_min <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(df_cut<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>quant)</span>
<span id="cb17-3">df_cut[quant<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span>quant_min, cut_min <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grepl</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'normal'</span>, dist),  <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">999</span>, </span>
<span id="cb17-4">                                           <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grepl</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'unif_shift'</span>, dist), <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))]</span>
<span id="cb17-5">df_cut[, .N, by<span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'dist'</span>]</span></code></pre></div></div>
<pre><code>##           dist  N
## 1:        beta 50
## 2:      normal 50
## 3: normal_wide 47
## 4:        unif 50
## 5:  unif_shift 50
## 6:        test 50</code></pre>
<blockquote class="blockquote">
<p>Simulated data points become sparse as moving to the two sides of the “normal_wide” distribution. Thus, when using <code>cut()</code>, some intervals are empty.</p>
</blockquote>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb19-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (dist_i <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'beta'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'normal'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'unif_shift'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'unif'</span>)) {</span>
<span id="cb19-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cat</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'# ----'</span>, dist_i, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'v.s. test ----'</span>)</span>
<span id="cb19-3">  test_group <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(df_cut[dist<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span>dist_i]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>cut_min, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x) df[dist<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'test'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>val<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span>x)</span>
<span id="cb19-4">  df_test <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.table</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'quant'</span><span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rowSums</span>(test_group), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'test'</span><span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span>df[dist<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'test'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>val)[</span>
<span id="cb19-5">    , .(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">test=</span>.N), by<span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'quant'</span>][<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">order</span>(quant)]</span>
<span id="cb19-6">  data_test <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">merge</span>(df_count[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'quant'</span>, dist_i), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">with=</span><span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>], df_test, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">by=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'quant'</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">all.x =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb19-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">setnafill</span>(data_test, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb19-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">print</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">chisq.test</span>(data_test[, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]))</span>
<span id="cb19-9">}</span></code></pre></div></div>
<pre><code>## # ---- beta v.s. test ----
##  Pearson's Chi-squared test
## 
## data:  data_test[, -1]
## X-squared = 14497, df = 49, p-value &lt; 2.2e-16
## 
## # ---- normal v.s. test ----
##  Pearson's Chi-squared test
## 
## data:  data_test[, -1]
## X-squared = 79504, df = 49, p-value &lt; 2.2e-16
## 
## # ---- unif_shift v.s. test ----
##  Pearson's Chi-squared test
## 
## data:  data_test[, -1]
## X-squared = 18099, df = 49, p-value &lt; 2.2e-16
## 
## # ---- unif v.s. test ----
##  Pearson's Chi-squared test
## 
## data:  data_test[, -1]
## X-squared = 35.413, df = 49, p-value = 0.9273</code></pre>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb21-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (dist_i <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'normal'</span>)) {</span>
<span id="cb21-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cat</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'# ----'</span>, dist_i, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'v.s. normal_wide ----'</span>)</span>
<span id="cb21-3">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># test_group: length of val by number of cuts</span></span>
<span id="cb21-4">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Create a list of booleans for each value in the test sequence</span></span>
<span id="cb21-5">  test_group <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(df_cut[dist<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span>dist_i]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>cut_min, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x) df[dist<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'normal_wide'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>val<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span>x)</span>
<span id="cb21-6">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># df_test: length of val by two =(aggregate by quant)=&gt; number of cuts by two</span></span>
<span id="cb21-7">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Identify the cutoff group for each value and </span></span>
<span id="cb21-8">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Count the number of values in each cutoff group</span></span>
<span id="cb21-9">  df_test <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.table</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'quant'</span><span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rowSums</span>(test_group), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'normal_wide'</span><span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span>df[dist<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'normal_wide'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>val)[</span>
<span id="cb21-10">    , .(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">normal_wide=</span>.N), by<span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'quant'</span>][<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">order</span>(quant)]</span>
<span id="cb21-11">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># data_test: number of cuts by three (i.e., quant, dist_target, dist_test)</span></span>
<span id="cb21-12">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Combine target and test sequence by cutoff groups</span></span>
<span id="cb21-13">  data_test <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">merge</span>(df_count[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'quant'</span>, dist_i), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">with=</span><span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>], df_test, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">by=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'quant'</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">all.x =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb21-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">setnafill</span>(data_test, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb21-15">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Execute Chi-squared test</span></span>
<span id="cb21-16">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">print</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">chisq.test</span>(data_test[, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]))</span>
<span id="cb21-17">}</span></code></pre></div></div>
<pre><code>## # ---- normal v.s. normal_wide ----
##  Pearson's Chi-squared test
## 
## data:  data_test[, -1]
## X-squared = 32200, df = 49, p-value &lt; 2.2e-16</code></pre>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Probability</category>
  <guid>https://yanghaowang.github.io/posts/compare-distributions/</guid>
  <pubDate>Fri, 13 Jan 2023 05:33:12 GMT</pubDate>
</item>
<item>
  <title>Extreme Value Distribution and Logit Regression</title>
  <link>https://yanghaowang.github.io/posts/extreme-value-logit/</link>
  <description><![CDATA[ 






<p><img src="https://yanghaowang.github.io/posts/extreme-value-logit/Logit.png" class="img-fluid"></p>
<p>Logit regression has been used a lot in modeling selection problems. To review its relationship with the extreme value distribution, it is better to derive the analytical form of Logit regression from its error assumption of type I extreme value distribution. Actually, this is a homework exercise from my Ph.D.&nbsp;econometrics course. It is a great chance to refresh my mind by doing this exercise again.</p>
<section id="generalized-extreme-value-distribution" class="level2">
<h2 class="anchored" data-anchor-id="generalized-extreme-value-distribution">Generalized Extreme Value Distribution</h2>
<p>Reference Link: <a href="https://en.wikipedia.org/wiki/Generalized_extreme_value_distribution">Generalized extreme value distribution - Wikipedia</a></p>
<p>Notions:</p>
<ul>
<li><p>Location parameter <img src="https://latex.codecogs.com/png.latex?%5Cmu%5Cin%5Cmathbb%20R"> and scale parameter <img src="https://latex.codecogs.com/png.latex?%5Csigma%3E0"></p></li>
<li><p>Standardized variable <img src="https://latex.codecogs.com/png.latex?s=(x-%5Cmu)/%5Csigma"></p></li>
<li><p>Cumulative distribution function</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AF(s)=%5Cexp%5Cleft(-%5Cexp%5Cleft(-s%5Cright)%5Cright)%0A"></p></li>
<li><p>Probability density function</p>
<p><img src="https://latex.codecogs.com/png.latex?%0Af(s)=%5Cexp%5Cleft(-s%5Cright)%5Cexp%5Cleft(-%5Cexp%5Cleft(-s%5Cright)%5Cright)%0A"></p></li>
</ul>
</section>
<section id="logit-function" class="level2">
<h2 class="anchored" data-anchor-id="logit-function">Logit Function</h2>
<section id="indirect-utility" class="level3">
<h3 class="anchored" data-anchor-id="indirect-utility">Indirect Utility</h3>
<p>Suppose the indirect utility of choosing alternative <img src="https://latex.codecogs.com/png.latex?i"> is specified as</p>
<p><img src="https://latex.codecogs.com/png.latex?%0Au_i=x_i%5Cbeta+%5Cvarepsilon_i%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?x_i"> is a vector of features of alternative <img src="https://latex.codecogs.com/png.latex?i"> and <img src="https://latex.codecogs.com/png.latex?%5Cvarepsilon_i"> follows the GEV.</p>
</section>
<section id="derivation" class="level3">
<h3 class="anchored" data-anchor-id="derivation">Derivation</h3>
<p>Alternative <img src="https://latex.codecogs.com/png.latex?i"> is selected if <img src="https://latex.codecogs.com/png.latex?u_i%5Cge%20u_k"> for any <img src="https://latex.codecogs.com/png.latex?k%5Cneq%20i">. Hence, the probability of choosing <img src="https://latex.codecogs.com/png.latex?i"> is</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5CPr(i)=%5Cint_%7B%5Cvarepsilon_i%7D%5Cprod_%7Bk%5Cneq%20i%7D%5CPr(%5Cvarepsilon_k%5Cle%20(x_i-x_k)%5Cbeta+%5Cvarepsilon_i)dF(%5Cvarepsilon_i).%0A"></p>
<p>Note that</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%5CPr(%5Cvarepsilon_k%5Cle%20(x_i-x_k)%5Cbeta+%5Cvarepsilon_i)%0A&amp;=%5Cexp%5Cleft(-%5Cexp%5Cleft(-(x_i-x_k)%5Cbeta-%5Cvarepsilon_i%5Cright)%5Cright)%20%5C%5C%0A&amp;=%5Cexp%5Cleft(-%5Cexp%5Cleft(-(x_i-x_k)%5Cbeta%5Cright)%5Ctimes%0A-%5Cexp%5Cleft(-%5Cvarepsilon_i%5Cright)%5Cright)%20%5C%5C%0A&amp;=%5Cleft%5B%5Cexp%5Cleft(-%5Cexp%5Cleft(-%5Cvarepsilon_i%5Cright)%5Cright)%5Cright%5D%5E%7Ba(x_k)%7D%20%5C%5C%0A%5Cend%7Balign*%7D%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?a(x_k)=%5Cexp%5Cleft(-(x_i-x_k)%5Cbeta%5Cright)="> is a constant.</p>
<p>The probability of choosing <img src="https://latex.codecogs.com/png.latex?i"> is then written as</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%5CPr(i)&amp;=%5Cint_%7B%5Cvarepsilon_i%7D%5Cprod_%7Bk%5Cneq%20i%7D%5Cleft%5B%5Cexp%5Cleft(-%5Cexp%5Cleft(-%5Cvarepsilon_i%5Cright)%5Cright)%5Cright%5D%5E%7Ba(x_k)%7DdF(%5Cvarepsilon_i)%5C%5C%0A&amp;=%5Cint_%7B%5Cvarepsilon_i%7D%5BF(%5Cvarepsilon_i)%5D%5E%7B%5Csum_%7Bk%5Cneq%20i%7D%20a(x_k)%7DdF(%5Cvarepsilon_i)%5C%5C%0A&amp;=%5Cleft.%5Cfrac%7B1%7D%7BA+1%7D%5BF(%5Cvarepsilon_i)%5D%5E%7BA+1%7D%5Cright%7C_%7B-%5Cinfty%7D%5E%7B+%5Cinfty%7D%5C%5C%0A&amp;=%5Cfrac%7B1%7D%7BA+1%7D%5BF(+%5Cinfty)%5D%5E%7BA+1%7D-%5Cfrac%7B1%7D%7BA+1%7D%5BF(-%5Cinfty)%5D%5E%7BA+1%7D%5C%5C%0A&amp;=%5Cfrac%7B1%7D%7BA+1%7D-0=%5Cfrac%7B1%7D%7B%5Csum_%7Bk%5Cneq%20i%7D%5Cexp%5Cleft(-(x_i-x_k)%5Cbeta%5Cright)+1%7D%5C%5C%0A&amp;=%5Cfrac%7B1%7D%7B%5Csum_%7Bk%5Cneq%20i%7D%5B%5Cexp%5Cleft(x_k%5Cbeta%5Cright)/%5Cexp%5Cleft(x_i%5Cbeta%5Cright)%5D+1%7D%5C%5C%0A&amp;=%5Cfrac%7B%5Cexp%5Cleft(x_i%5Cbeta%5Cright)%7D%7B%5Csum_%7Bk%5Cneq%20i%7D%5Cexp%5Cleft(x_k%5Cbeta%5Cright)+%5Cexp%5Cleft(x_i%5Cbeta%5Cright)%7D%0A%5Cend%7Balign*%7D,%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?A=%5Csum_ka(x_k)">, <img src="https://latex.codecogs.com/png.latex?F(+%5Cinfty)=%5Cexp%5Cleft(-%5Cexp%5Cleft(-%5Cinfty%5Cright)%5Cright)=1">, and <img src="https://latex.codecogs.com/png.latex?F(-%5Cinfty)=0">.</p>
</section>
<section id="logit-regression" class="level3">
<h3 class="anchored" data-anchor-id="logit-regression">Logit Regression</h3>
<p>Reference Link: <a href="https://en.wikipedia.org/wiki/Logistic_regression">Logistic regression - Wikipedia</a></p>
<p>Let one of the alternatives be an opt-out and normalize the opt-out be zero. The logit form is given by</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5CPr(i)=%5Cfrac%7B%5Cexp%5Cleft(x_i%5Cbeta%5Cright)%7D%7B%5Csum_%7Bj%5Cin%20S%7D%5Cexp%5Cleft(x_j%5Cbeta%5Cright)+1%7D%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?S=%5C%7B1,2,%5Cdots,i,j,%5Cdots,J%5C%7D"> is a set of mutually exclusive alternatives included in the analysis.</p>


</section>
</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Probability</category>
  <guid>https://yanghaowang.github.io/posts/extreme-value-logit/</guid>
  <pubDate>Tue, 03 Jan 2023 07:17:54 GMT</pubDate>
</item>
<item>
  <title>Conditional Probability Application: Association Rule Learning</title>
  <link>https://yanghaowang.github.io/posts/conditional-prob-association-rules/</link>
  <description><![CDATA[ 






<p><img src="https://yanghaowang.github.io/posts/conditional-prob-association-rules/AssociationRule_Pic.png" class="img-fluid"></p>
<p>“Association rule learning is a rule-based machine learning method for discovering interesting relations between variables in large databases. … In any given transaction with a variety of items, association rules are meant to discover the rules that determine how or why certain items are connected.” – <a href="https://en.wikipedia.org/wiki/Association_rule_learning">Wikipedia</a></p>
<p>This post briefly covers the following metrics:</p>
<ul>
<li><p><strong>Support</strong> is the evidence of how frequently an item appears in the data given</p></li>
<li><p><strong>Confidence</strong> is defined by how many times the if-then statements are found true</p></li>
<li><p><strong>Lift</strong> is used to compare the expected Confidence (assume X and Y are independent) and the actual Confidence (think of the lift formula and divide <img src="https://latex.codecogs.com/png.latex?%5Ctext%7Bsupp%7D(X)"> for both the numerator and denominator)</p></li>
</ul>
<section id="support" class="level2">
<h2 class="anchored" data-anchor-id="support">Support</h2>
<p>The support of <img src="https://latex.codecogs.com/png.latex?X"> with respect to <img src="https://latex.codecogs.com/png.latex?T"> is defined as the proportion of transactions in the dataset which contains the itemset (or item) <img src="https://latex.codecogs.com/png.latex?X">:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Ctext%7BSupport%20of%20$X$%7D=%5Cfrac%7B%5C%7B(i,t)%5Cin%20T:X%5Csubseteq%20t%5C%7D%7D%7B%7CT%7C%7D%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?i"> is the transaction ID and <img src="https://latex.codecogs.com/png.latex?t"> is its full itemset.</p>
<p>Example, the support of <img src="https://latex.codecogs.com/png.latex?%5C%7BA,B%5C%7D">:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Ctext%7BSupport%7D=P(A%5Ccap%20B)=%5Cfrac%7B%5Ctext%7Bnumber%20of%20trans%20containing%20$A$%20and%20$B$%7D%7D%0A%7B%5Ctext%7Btotal%20number%20of%20trans%7D%7D%0A"></p>
</section>
<section id="confidence" class="level2">
<h2 class="anchored" data-anchor-id="confidence">Confidence</h2>
<p>With respect to <img src="https://latex.codecogs.com/png.latex?T">, the confidence value of an association rule, often denoted as <img src="https://latex.codecogs.com/png.latex?X%5CRightarrow%20Y">, is the ratio of transactions containing both <img src="https://latex.codecogs.com/png.latex?X"> and <img src="https://latex.codecogs.com/png.latex?Y"> to the total amount of <img src="https://latex.codecogs.com/png.latex?X"> values present, where <img src="https://latex.codecogs.com/png.latex?X"> is the antecedent and <img src="https://latex.codecogs.com/png.latex?Y"> is the consequent.</p>
<p>Confidence can also be interpreted as an estimate of the conditional probability <img src="https://latex.codecogs.com/png.latex?P(E_Y%5Cmid%20E_X)">.</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%5Ctext%7Bconf%7D(X%5CRightarrow%20Y)=&amp;%20P(Y%5Cmid%20X)=%5Cfrac%7B%5Ctext%7Bsupp%7D(X%5Ccap%20Y)%7D%7B%5Ctext%7Bsupp%7D(X)%7D%0A%5C%5C=&amp;%5Cfrac%7B%5Ctext%7Bnumber%20of%20trans%20containing%20$X$%20and%20$Y$%7D%7D%7B%5Ctext%7Bnumber%20of%20trans%20containing%20%7D%20X%7D%0A%5Cend%7Balign*%7D%0A"></p>
<section id="example" class="level3">
<h3 class="anchored" data-anchor-id="example">Example</h3>
<p><strong>Data</strong> (5 Transactions and 5 Items)</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Transaction ID</th>
<th>milk</th>
<th>bread</th>
<th>butter</th>
<th>egg</th>
<th>fruit</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>1</td>
<td>1</td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
<tr class="even">
<td>2</td>
<td>0</td>
<td>0</td>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr class="odd">
<td>3</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr class="even">
<td>4</td>
<td>1</td>
<td>1</td>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr class="odd">
<td>5</td>
<td>0</td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
</tbody>
</table>
<p><strong>Support and Confidence</strong></p>
<table class="caption-top table">
<colgroup>
<col style="width: 48%">
<col style="width: 11%">
<col style="width: 12%">
<col style="width: 27%">
</colgroup>
<thead>
<tr class="header">
<th>if Antecedent then Consequent</th>
<th>supp</th>
<th>conf</th>
<th>supp X conf</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>if buy milk, then buy bread</td>
<td><img src="https://latex.codecogs.com/png.latex?2/5=0.4"></td>
<td><img src="https://latex.codecogs.com/png.latex?2/2=1.0"></td>
<td><img src="https://latex.codecogs.com/png.latex?0.4%5Ctimes1.0=0.4"></td>
</tr>
<tr class="even">
<td>if buy milk, then buy eggs</td>
<td><img src="https://latex.codecogs.com/png.latex?1/5=0.2"></td>
<td><img src="https://latex.codecogs.com/png.latex?1/2=0.5"></td>
<td><img src="https://latex.codecogs.com/png.latex?0.2%5Ctimes0.5=0.1"></td>
</tr>
<tr class="odd">
<td>if buy bread, then buy fruit</td>
<td><img src="https://latex.codecogs.com/png.latex?2/5=0.4"></td>
<td><img src="https://latex.codecogs.com/png.latex?2/3=0.66"></td>
<td><img src="https://latex.codecogs.com/png.latex?0.4%5Ctimes0.66=0.264"></td>
</tr>
<tr class="even">
<td>if buy fruit, then buy eggs</td>
<td><img src="https://latex.codecogs.com/png.latex?2/5=0.4"></td>
<td><img src="https://latex.codecogs.com/png.latex?2/3=0.66"></td>
<td><img src="https://latex.codecogs.com/png.latex?0.4%5Ctimes0.66=0.264"></td>
</tr>
<tr class="odd">
<td>if buy milk and bread, then buy fruit</td>
<td><img src="https://latex.codecogs.com/png.latex?2/5=0.4"></td>
<td><img src="https://latex.codecogs.com/png.latex?2/2=%201.0"></td>
<td><img src="https://latex.codecogs.com/png.latex?0.4%5Ctimes1.0=0.4"></td>
</tr>
</tbody>
</table>
<ul>
<li><p>Itemset <img src="https://latex.codecogs.com/png.latex?%5C%7B%5Ctext%7Bmilk,bread%7D%5C%7D"> has a support of 0.4 since it occurs in 40% of all transactions.</p></li>
<li><p>The rule <img src="https://latex.codecogs.com/png.latex?%5C%7B%5Ctext%7Bmilk,bread%7D%5C%7D%5CRightarrow%5C%7B%5Ctext%7Bbutter%7D%5C%7D"> has a confidence value of <img src="https://latex.codecogs.com/png.latex?%5Cfrac%7B1/5%7D%7B2/5%7D=0.5">, suggesting butter is bought 50% of the times when milk and bread are bought.</p></li>
</ul>
</section>
</section>
<section id="lift" class="level2">
<h2 class="anchored" data-anchor-id="lift">Lift</h2>
<p>The ratio of the observed support to that expected if <img src="https://latex.codecogs.com/png.latex?X"> and <img src="https://latex.codecogs.com/png.latex?Y"> were independent:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Ctext%7Blift%7D(X%5CRightarrow%20Y)=%5Cfrac%7B%5Ctext%7Bsupp%7D(X%5Ccap%20Y)%7D%7B%5Ctext%7Bsupp%7D(X)%5Ctimes%5Ctext%7Bsupp%7D(Y)%7D%0A"></p>
<p>For example, the rule <img src="https://latex.codecogs.com/png.latex?%5C%7B%5Ctext%7Bmilk,bread%7D%5C%7D%5CRightarrow%5C%7B%5Ctext%7Bbutter%7D%5C%7D"> has a lift of <img src="https://latex.codecogs.com/png.latex?%5Cfrac%7B0.2%7D%7B0.4%5Ctimes%200.4%7D=1.25"></p>
<table class="caption-top table">
<colgroup>
<col style="width: 17%">
<col style="width: 82%">
</colgroup>
<thead>
<tr class="header">
<th></th>
<th>Implied Relation</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><img src="https://latex.codecogs.com/png.latex?%5Ctext%7Blift%7D=1"></td>
<td>Independent</td>
</tr>
<tr class="even">
<td><img src="https://latex.codecogs.com/png.latex?%5Ctext%7Blift%7D%3E1"></td>
<td>The degree to which those two occurrences are dependent on one another</td>
</tr>
<tr class="odd">
<td><img src="https://latex.codecogs.com/png.latex?%5Ctext%7Blift%7D%3C1"></td>
<td>The degree to which the items are substitute to each other</td>
</tr>
</tbody>
</table>
</section>
<section id="summary" class="level2">
<h2 class="anchored" data-anchor-id="summary">Summary</h2>
<ul>
<li><p>If the rules were built from analyzing all the possible itemsets from the data then there would be so many rules that they wouldn’t have any meaning. That is why Association rules are typically made from rules that are well-represented by the data</p>
<ul>
<li>When using Association rules, you are most likely to only use Support and Confidence. However, this means you have to satisfy a <em>user-specified minimum support</em> and a <em>user-specified minimum confidence</em> at the same time.</li>
</ul></li>
<li><p><strong>Benefit</strong></p>
<p>Find the pattern that helps understand the correlations and co-occurrences between data sets. A very good real-world example that uses Association rules would be medicine. Medicine uses Association rules to help diagnose patients. [symptoms =&gt; illness]</p></li>
<li><p><strong>Downfalls</strong></p>
<ul>
<li><p>Find the appropriate parameter and threshold settings for the mining algorithm</p></li>
<li><p>Have a large number of discovered rules, for which the algorithm does not guarantee the relevancy/reliability</p></li>
</ul></li>
</ul>
</section>
<section id="r-package-and-tutorial" class="level2">
<h2 class="anchored" data-anchor-id="r-package-and-tutorial">R Package and Tutorial</h2>
<p><a href="https://cran.r-project.org/web/packages/arules/index.html">CRAN - Package arules</a></p>
<p><a href="https://michael.hahsler.net/research/arules_RUG_2015/talk/arules_RUG2015.pdf">arules: Association Rule Mining with R - A Tutorial (PDF File)</a></p>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Probability</category>
  <guid>https://yanghaowang.github.io/posts/conditional-prob-association-rules/</guid>
  <pubDate>Tue, 06 Dec 2022 06:06:56 GMT</pubDate>
</item>
<item>
  <title>Sample Size: Testing or Survey</title>
  <link>https://yanghaowang.github.io/posts/sample-size-testing/</link>
  <description><![CDATA[ 






<p><img src="https://yanghaowang.github.io/posts/sample-size-testing/SampleSizePieChart.jpeg" class="img-fluid"></p>
<p>This is a summary note on calculating sample size for different purposes. The detailed derivation of the sample size for an AB testing with two-independent groups can be found <a href="https://yanghaowang.github.io/posts/20220830-Derivation-of-Sample-Size-for-Two-group-AB-Testing">here</a>.</p>
<section id="ab-testing" class="level2">
<h2 class="anchored" data-anchor-id="ab-testing">AB Testing</h2>
<p>Let the test statistic be significant at <img src="https://latex.codecogs.com/png.latex?%5Calpha"> with a statistical power of <img src="https://latex.codecogs.com/png.latex?1-%5Cbeta">. <strong>The sample size formula for each group</strong> is given by</p>
<p><img src="https://latex.codecogs.com/png.latex?%0An%5Capprox%5Cfrac%7Br+1%7D%7Br%7D%0A%5Cfrac%7B%5Cbar%20p(1-%5Cbar%20p)(z_%7B1-%5Calpha%7D+z_%7B1-%5Cbeta%7D)%5E2%7D%7B%5Cdelta%5E2%7D%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?r"> is the size ratio of the larger group over the smaller group.</p>
<ul>
<li><p><strong>Two Independent Groups</strong></p>
<p>Suppose the proportion rate <img src="https://latex.codecogs.com/png.latex?p_1"> in the treatment group is not much different from the proportion rate <img src="https://latex.codecogs.com/png.latex?p_0"> in the control group. Then, we have <img src="https://latex.codecogs.com/png.latex?%5Cbar%20p%20=(p_0+p_1)/2">, and <img src="https://latex.codecogs.com/png.latex?%5Cdelta=p_0-p_1">. The total sample size including the treatment and the control is <img src="https://latex.codecogs.com/png.latex?2n">.</p>
<ul>
<li><p><strong>One-tailed</strong></p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?z_%7B1-%5Calpha%7D"> is the critical value</li>
</ul>
<blockquote class="blockquote">
<p>Here is a link to an <a href="https://datasciencegenie.com/how-to-calculate-the-sample-size-for-an-a-b-testing-including-calculator-derivation/">Online Calculator at DataSciencEgenie.</a></p>
</blockquote></li>
<li><p><strong>Two-tailed</strong></p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?z_%7B1-%5Calpha/2%7D"> is used rather than <img src="https://latex.codecogs.com/png.latex?z_%7B1-%5Calpha%7D"></li>
</ul>
<blockquote class="blockquote">
<p>Here are links to <a href="https://clincalc.com/Stats/SampleSize.aspx">Online Calculator at ClinCalc</a> and <a href="https://www.evanmiller.org/ab-testing/sample-size.html">Evan’s Awesome A/B Tools.</a></p>
</blockquote></li>
<li><p><strong>Two equal-size groups</strong></p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?r=1"> <img src="https://latex.codecogs.com/png.latex?%0An%5Capprox%202%5Ctimes%5Cfrac%7B%5Cbar%20p(1-%5Cbar%20p)(z_%7B1-%5Calpha%7D+z_%7B1-%5Cbeta%7D)%5E2%7D%7B%5Cdelta%5E2%7D%0A"></li>
</ul></li>
</ul></li>
<li><p><strong>Population v.s. One Study Group</strong></p>
<p>Suppose the population proportion is known at <img src="https://latex.codecogs.com/png.latex?%5Cbar%20p">. We have <img src="https://latex.codecogs.com/png.latex?%5Cdelta=p_%7B%5Ctext%7Bstudy%20group%7D%7D-%5Cbar%20p"> and <img src="https://latex.codecogs.com/png.latex?%5Clim_%7Br%5Crightarrow%5Cinfty%7D(r+1)/r=1">. The sample size of the study group is <img src="https://latex.codecogs.com/png.latex?n">.</p>
<p><img src="https://latex.codecogs.com/png.latex?%0An%5Capprox%20%5Cfrac%7B%5Cbar%20p(1-%5Cbar%20p)(z_%7B1-%5Calpha%7D+z_%7B1-%5Cbeta%7D)%5E2%7D%7B%5Cdelta%5E2%7D%0A"></p>
<blockquote class="blockquote">
<p>Here is a link to an <a href="https://clincalc.com/Stats/SampleSize.aspx">Online Calculator at ClinCalc.</a></p>
</blockquote></li>
</ul>
</section>
<section id="survey" class="level2">
<h2 class="anchored" data-anchor-id="survey">Survey</h2>
<p>In a survey, we care about the result representativeness, that is, if the sample mean from the survey can represent the population mean.</p>
<p>Ideally, we would like our survey proportion <img src="https://latex.codecogs.com/png.latex?p'"> to be the same as the true proportion <img src="https://latex.codecogs.com/png.latex?p"> from the population. In fact, we allow the survey estimate <img src="https://latex.codecogs.com/png.latex?%5Chat%20p'"> is close to the true proportion within a margin of error less than <img src="https://latex.codecogs.com/png.latex?%5Cdelta"> at a confidence level of <img src="https://latex.codecogs.com/png.latex?1-%5Calpha">. This problem can be set up in a hypothesis test as below:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0AH_0&amp;:%20p%20=%20p',%20%5C%5C%0AH_1&amp;:%20p%20%5Cneq%20p'.%0A%5Cend%7Balign*%7D%0A"></p>
<p>The sampling distribution of the difference, <img src="https://latex.codecogs.com/png.latex?%5Chat%20p'-p">, is given by</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Chat%20p'%20-%20p%20%5Csim%20N%5Cleft(p'-p,%0A%5Cfrac%7Bp'(1-p')%7D%7Bn%7D%20%5Cright).%0A"></p>
<p>Therefore,</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AZ=%5Cfrac%7B(%5Chat%20p'-p)-(p'-p)%7D%0A%7B%5Csqrt%7B%5Cfrac%7Bp'(1-p')%7D%7Bn%7D%7D%7D%5Csim%20N(0,1).%0A"></p>
<p>The confidence level suggests</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%5CPr(H_0%20%5Ctext%7B%20cannot%20be%20rejected%7D%5Cmid%20H_0%5Ctext%7B%20is%20true%7D)&amp;=1-%5Calpha%20%5C%5C%0A%5CPr(Z%20%5Cge%20%20z_%7B%5Calpha/2%7D%20%5Cmid%20H_0%5Ctext%7B%20is%20true%7D)&amp;=1-%5Calpha/2%20%5C%5C%0A%5CPr%5Cleft(%5Cfrac%7B(%5Chat%20p'-p)-(p'-p)%7D%0A%7B%5Csqrt%7B%5Cfrac%7Bp'(1-p')%7D%7Bn%7D%7D%7D%5Cge%20z_%7B%5Calpha/2%7D%0A%5Cmid%20%20H_0%5Ctext%7B%20is%20true%7D%5Cright)%20&amp;=%201%20-%5Calpha/2%20%5C%5C%0A%5CPr%5Cleft(%5Cfrac%7B(%5Chat%20p'-p)%7D%0A%7B%5Csqrt%7B%5Cfrac%7Bp(1-p)%7D%7Bn%7D%7D%7D%5Cge%20z_%7B%5Calpha/2%7D%5Cright)%20&amp;=%201%20-%5Calpha/2%0A%5Cend%7Balign*%7D%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?p'=p"> if <img src="https://latex.codecogs.com/png.latex?H_0"> is true. Since we allow our estimate <img src="https://latex.codecogs.com/png.latex?%5Chat%20p'"> to be close to <img src="https://latex.codecogs.com/png.latex?p"> within a distance of <img src="https://latex.codecogs.com/png.latex?%5Cdelta">, we have</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A&amp;%5Cfrac%7B%5Cdelta%7D%7B%5Csqrt%7B%5Cfrac%7Bp(1-p)%7D%7Bn%7D%7D%7D%5Cge%5Cfrac%7B(%5Chat%20p'-p)%7D%7B%5Csqrt%7B%5Cfrac%7Bp(1-p)%7D%7Bn%7D%7D%7D%5Cge%20z_%7B%5Calpha/2%7D%0A%5C%5C%0A&amp;%5Cdelta%5E2%20%5Cge%20z_%7B%5Calpha/2%7D%5E2%5Ctimes%5Cfrac%7Bp(1-p)%7D%7Bn%7D%20%5Cimplies%0An%5Cge%20%5Cfrac%7Bz_%7B%5Calpha/2%7D%5E2%5Ctimes%20p(1-p)%7D%7B%5Cdelta%5E2%7D.%0A%5Cend%7Balign*%7D%0A"></p>
<p>The minimal survey size is given by</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cfrac%7Bz_%7B%5Calpha/2%7D%5E2%5Ctimes%20p(1-p)%7D%7B%5Cdelta%5E2%7D.%0A"></p>
<blockquote class="blockquote">
<p>Here is a link to an <a href="https://www.calculator.net/sample-size-calculator.html">Online Calculator at Calculator.</a></p>
</blockquote>
</section>
<section id="z-critical-values" class="level2">
<h2 class="anchored" data-anchor-id="z-critical-values">Z Critical Values</h2>
<p>The following table presents a list of commonly used Z scores (also known as critical values) in practice.</p>
<table class="caption-top table">
<colgroup>
<col style="width: 11%">
<col style="width: 44%">
<col style="width: 44%">
</colgroup>
<thead>
<tr class="header">
<th><img src="https://latex.codecogs.com/png.latex?%5Calpha"></th>
<th style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?z_%7B1-%5Calpha%7D">&nbsp;(Right-tailed)</th>
<th style="text-align: center;"><img src="https://latex.codecogs.com/png.latex?z_%7B1-%5Calpha/2%7D">&nbsp;(Two-tailed)</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>0.01</td>
<td style="text-align: center;">2.326</td>
<td style="text-align: center;">+/-2.576</td>
</tr>
<tr class="even">
<td>0.05</td>
<td style="text-align: center;">1.645</td>
<td style="text-align: center;">+/-1.960</td>
</tr>
<tr class="odd">
<td>0.10</td>
<td style="text-align: center;">1.282</td>
<td style="text-align: center;">+/-1.645</td>
</tr>
<tr class="even">
<td>0.20</td>
<td style="text-align: center;">0.842</td>
<td style="text-align: center;">+/-1.282</td>
</tr>
</tbody>
</table>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>A/B Testing</category>
  <category>Hypothesis Testing</category>
  <category>Sample Size</category>
  <guid>https://yanghaowang.github.io/posts/sample-size-testing/</guid>
  <pubDate>Fri, 02 Sep 2022 07:17:55 GMT</pubDate>
</item>
<item>
  <title>Derivation of Sample Size for Two-group AB Testing</title>
  <link>https://yanghaowang.github.io/posts/sample-size-ab-testing/</link>
  <description><![CDATA[ 






<p><img src="https://yanghaowang.github.io/posts/sample-size-ab-testing/SampleSize_ABTesting.png" class="img-fluid"></p>
<section id="problem-settings" class="level2">
<h2 class="anchored" data-anchor-id="problem-settings">Problem Settings</h2>
<ul>
<li><p><strong>Two independent</strong> groups</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th></th>
<th>Control</th>
<th>Treatment</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Size</td>
<td><img src="https://latex.codecogs.com/png.latex?n_0"></td>
<td><img src="https://latex.codecogs.com/png.latex?n1"></td>
</tr>
<tr class="even">
<td>Percentage<br>of Interest</td>
<td><img src="https://latex.codecogs.com/png.latex?p_0"></td>
<td><img src="https://latex.codecogs.com/png.latex?p_1"></td>
</tr>
</tbody>
</table></li>
<li><p><mark>One-tailed</mark> hypothesis testing</p>
<ul>
<li><p><img src="https://latex.codecogs.com/png.latex?H_0:%20%5Cspace%20p_0=p_1"></p></li>
<li><p><img src="https://latex.codecogs.com/png.latex?H_1:%20%5Cspace%20p_0%3Cp_1"></p></li>
<li><p>Significance level (type I error): <img src="https://latex.codecogs.com/png.latex?%5Calpha"></p></li>
<li><p>Statistical power (1 - type II error): <img src="https://latex.codecogs.com/png.latex?1-%5Cbeta"></p></li>
<li><p>Percentage of Interest in sample: <img src="https://latex.codecogs.com/png.latex?%5Chat%20p_0"> and <img src="https://latex.codecogs.com/png.latex?%5Chat%20p_1"></p></li>
</ul></li>
</ul>
<p>The sampling distribution of the difference, <img src="https://latex.codecogs.com/png.latex?%5Chat%20p_0-%5Chat%20p_1">, is given by</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Chat%20p_0%20-%20%5Chat%20p_1%20%5Csim%20N%5Cleft(p_0-p_1,%0A%5Cfrac%7Bp_0(1-p_0)%7D%7Bn_0%7D+%5Cfrac%7Bp_1(1-p_1)%7D%7Bn_1%7D%20%5Cright).%0A"></p>
<p>Therefore,</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AZ=%5Cfrac%7B(%5Chat%20p_0-%5Chat%20p_1)-(p_0-p_1)%7D%0A%7B%5Csqrt%7B%5Cfrac%7Bp_0(1-p_0)%7D%7Bn_0%7D+%5Cfrac%7Bp_1(1-p_1)%7D%7Bn_1%7D%7D%7D%5Csim%20N(0,1)%0A"></p>
</section>
<section id="type-i-error-in-testing" class="level2">
<h2 class="anchored" data-anchor-id="type-i-error-in-testing">Type I Error in Testing</h2>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%5CPr(H_0%20%5Ctext%7B%20is%20rejected%7D%5Cmid%20H_0%5Ctext%7B%20is%20true%7D)&amp;=%5Calpha%20%5C%5C%0A%5CPr(H_0%20%5Ctext%7B%20cannot%20be%20rejected%7D%5Cmid%20H_0%5Ctext%7B%20is%20true%7D)&amp;=1-%5Calpha%20%5C%5C%0A%5CPr(Z%20%3C%20z_%7B1-%5Calpha%7D%20%5Cmid%20H_0%5Ctext%7B%20is%20true%7D)&amp;=1-%5Calpha%20%5C%5C%0A%5CPr%5Cleft(%5Cfrac%7B(%5Chat%20p_0-%5Chat%20p_1)-(p_0-p_1)%7D%0A%7B%5Csqrt%7B%5Cfrac%7Bp_0(1-p_0)%7D%7Bn_0%7D+%5Cfrac%7Bp_1(1-p_1)%7D%7Bn_1%7D%7D%7D%3Cz_%7B1-%5Calpha%7D%0A%5Cmid%20%20H_0%5Ctext%7B%20is%20true%7D%5Cright)%20&amp;=%201%20-%5Calpha%20%5C%5C%0A%5Cend%7Balign*%7D%0A"></p>
<p>Given <img src="https://latex.codecogs.com/png.latex?H_0"> is true, we have <img src="https://latex.codecogs.com/png.latex?p_0=p_1=p=%5Cfrac%7Bn_0p_0+n_1p_1%7D%7Bn_0+n_1%7D">. Hence, the conditional probability can be written as an unconditional probability, such that,</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%5CPr%5Cleft(%5Cfrac%7B(%5Chat%20p_0-%5Chat%20p_1)%7D%0A%7B%5Csqrt%7Bp(1-p)%5Cleft(%5Cfrac%7B1%7D%7Bn_0%7D+%5Cfrac%7B1%7D%7Bn_1%7D%5Cright)%7D%7D%3Cz_%7B1-%5Calpha%7D%0A%5Cright)%20&amp;=%201%20-%5Calpha%20%5C%5C%0A%5CPr%5Cleft(%5Chat%20p_0-%5Chat%20p_1%0A%3Cz_%7B1-%5Calpha%7D%20%5Csqrt%7Bp(1-p)%5Cleft(%5Cfrac%7B1%7D%7Bn_0%7D+%5Cfrac%7B1%7D%7Bn_1%7D%5Cright)%7D%0A%5Cright)%20&amp;=%201%20-%5Calpha.%0A%5Cend%7Balign*%7D%0A"></p>
<p>If we have <mark>two equal-size groups</mark>, i.e., <img src="https://latex.codecogs.com/png.latex?n_0=n_1=n">, then <img src="https://latex.codecogs.com/png.latex?%5Chat%20p=(%5Chat%20p_0+%20%5Chat%20p_1)/2"> and</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5CPr%5Cleft(%5Chat%20p_0-%5Chat%20p_1%0A%3Cz_%7B1-%5Calpha%7D%20%5Csqrt%7B%5Cfrac%7B%5Chat%20p_0+%20%5Chat%20p_1%7D%7B2%7D(1-%5Cfrac%7B%5Chat%20p_0+%20%5Chat%20p_1%7D%7B2%7D)%5Cfrac%7B2%7D%7Bn%7D%7D%0A%5Cright)%20=%201%20-%5Calpha.%0A"></p>
</section>
<section id="type-ii-error-in-testing" class="level2">
<h2 class="anchored" data-anchor-id="type-ii-error-in-testing">Type II Error in Testing</h2>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%5CPr(H_0%20%5Ctext%7B%20cannot%20be%20rejected%7D%5Cmid%20H_1%5Ctext%7B%20is%20true%7D)&amp;=%5Cbeta%20%5C%5C%0A%5CPr(H_0%20%5Ctext%7B%20is%20rejected%7D%5Cmid%20H_1%5Ctext%7B%20is%20true%7D)&amp;=1-%20%5Cbeta%5C%5C%0A%5CPr%5Cleft(%5Chat%20p_0-%5Chat%20p_1%0A%3Ez_%7B1-%5Calpha%7D%20%5Csqrt%7B%5Cfrac%7B%5Chat%20p_0+%20%5Chat%20p_1%7D%7B2%7D(1-%5Cfrac%7B%5Chat%20p_0+%20%5Chat%20p_1%7D%7B2%7D)%5Cfrac%7B2%7D%7Bn%7D%7D%0A%5Cmid%20H_1%5Ctext%7B%20is%20true%7D%5Cright)&amp;=1-%20%5Cbeta%5C%5C%0A%5Cend%7Balign*%7D%0A"></p>
<p>Since <img src="https://latex.codecogs.com/png.latex?H_1"> is true, we have <img src="https://latex.codecogs.com/png.latex?p_0%3Cp_1">. In particular, let <img src="https://latex.codecogs.com/png.latex?p_0%20-%20p_1%20=%20%5Cdelta">. Then, we can rewrite the distribution to a standard normal distribution, such that,</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%5CPr%5Cleft(%5Cfrac%7B%5Chat%20p_0-%5Chat%20p_1%20-%7B%5Cdelta%7D%7D%0A%7B%5Csqrt%7B%5Cfrac%7B%5Chat%20p_0(1-%5Chat%20p_0)%7D%7Bn%7D+%5Cfrac%7B%5Chat%20p_1(1-%5Chat%20p_1)%7D%7Bn%7D%7D%7D%0A%3E%5Cfrac%7Bz_%7B1-%5Calpha%7D%20%5Csqrt%7B%5Cfrac%7B%5Chat%20p_0+%20%5Chat%20p_1%7D%7B2%7D(1-%5Cfrac%7B%5Chat%20p_0+%20%5Chat%20p_1%7D%7B2%7D)%5Cfrac%7B2%7D%7Bn%7D%7D%0A-%7B%5Cdelta%7D%7D%0A%7B%5Csqrt%7B%5Cfrac%7B%5Chat%20p_0(1-%5Chat%20p_0)%7D%7Bn%7D+%5Cfrac%7B%5Chat%20p_1(1-%5Chat%20p_1)%7D%7Bn%7D%7D%7D%5Cright)&amp;=1-%20%5Cbeta%5C%5C%0A%5CPr%5Cleft(Z%3E%5Cfrac%7Bz_%7B1-%5Calpha%7D%20%5Csqrt%7B%5Cfrac%7B%5Chat%20p_0+%20%5Chat%20p_1%7D%7B2%7D(1-%5Cfrac%7B%5Chat%20p_0+%20%5Chat%20p_1%7D%7B2%7D)%5Cfrac%7B2%7D%7Bn%7D%7D%0A-%5Cdelta%7D%0A%7B%5Csqrt%7B%5Cfrac%7B%5Chat%20p_0(1-%5Chat%20p_0)%7D%7Bn%7D+%0A%5Cfrac%7B%5Chat%20p_1(1-%5Chat%20p_1)%7D%7Bn%7D%7D%7D%5Cright)&amp;=1-%5Cbeta%0A%5Cend%7Balign*%7D%0A"></p>
</section>
<section id="solve-equation-for-n" class="level2">
<h2 class="anchored" data-anchor-id="solve-equation-for-n">Solve Equation for n</h2>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%5Cfrac%7Bz_%7B1-%5Calpha%7D%20%5Csqrt%7B%5Cfrac%7B%5Chat%20p_0+%20%5Chat%20p_1%7D%7B2%7D(1-%5Cfrac%7B%5Chat%20p_0+%20%5Chat%20p_1%7D%7B2%7D)%5Cfrac%7B2%7D%7Bn%7D%7D%0A-%5Cdelta%7D%0A%7B%5Csqrt%7B%5Cfrac%7B%5Chat%20p_0(1-%5Chat%20p_0)%7D%7Bn%7D+%0A%5Cfrac%7B%5Chat%20p_1(1-%5Chat%20p_1)%7D%7Bn%7D%7D%7D=%20z_%7B%5Cbeta%7D=-z_%7B1-%5Cbeta%7D%20%5C%5C%0A%5Cfrac%7Bz_%7B1-%5Calpha%7D%20%5Csqrt%7B2%5Ctimes%5Cfrac%7B%5Chat%20p_0+%20%5Chat%20p_1%7D%7B2%7D(1-%5Cfrac%7B%5Chat%20p_0+%20%5Chat%20p_1%7D%7B2%7D)%7D%0A-%5Cdelta%5Csqrt%7Bn%7D%7D%0A%7B%5Csqrt%7B(%5Chat%20p_0(1-%5Chat%20p_0))+(%5Chat%20p_1(1-%5Chat%20p_1))%7D%7D=%20-z_%7B1-%5Cbeta%7D%20%5C%5C%0A%5Cend%7Balign*%7D%0A"></p>
<p>That is,</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0Az_%7B1-%5Calpha%7D%20%5Csqrt%7B2%5Ctimes%5Cfrac%7B%5Chat%20p_0+%20%5Chat%20p_1%7D%7B2%7D(1-%5Cfrac%7B%5Chat%20p_0+%20%5Chat%20p_1%7D%7B2%7D)%7D%0A-%5Cdelta%5Csqrt%7Bn%7D=%20-z_%7B1-%5Cbeta%7D%5Csqrt%7B(%5Chat%20p_0(1-%5Chat%20p_0))+(%5Chat%20p_1(1-%5Chat%20p_1))%7D%20%5C%5C%0A%5Cimplies%20n%20=%0A%5Cfrac%7B%5Cleft(z_%7B1-%5Calpha%7D%20%5Csqrt%7B2%5Ctimes%5Cfrac%7B%5Chat%20p_0+%20%5Chat%20p_1%7D%7B2%7D(1-%5Cfrac%7B%5Chat%20p_0+%20%5Chat%20p_1%7D%7B2%7D)%7D%0A+%20z_%7B1-%5Cbeta%7D%5Csqrt%7B(%5Chat%20p_0(1-%5Chat%20p_0))+(%5Chat%20p_1(1-%5Chat%20p_1))%7D%0A%5Cright)%5E2%7D%0A%7B%5Cdelta%5E2%7D.%0A%5Cend%7Balign*%7D%0A"></p>
<ul>
<li><p><mark>n is the sample size for each group.</mark> In other words, the total sample size is <img src="https://latex.codecogs.com/png.latex?2n">.</p></li>
<li><p><mark><img src="https://latex.codecogs.com/png.latex?z_%7B1-%5Calpha%7D"></mark> is the critical value at the significance level of <img src="https://latex.codecogs.com/png.latex?%5Calpha"> in a <mark>one-tailed</mark> test.</p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?z_%7B1-%5Calpha%7D"> will be replaced with <mark><img src="https://latex.codecogs.com/png.latex?z_%7B1-%5Calpha/2%7D"> in a two-tailed</mark> test.</li>
</ul></li>
</ul>
<p>Suppose <img src="https://latex.codecogs.com/png.latex?%5Chat%20p_0"> and <img src="https://latex.codecogs.com/png.latex?%5Chat%20p_1"> are quite similar, we have</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cfrac%7B%5Chat%20p_0+%20%5Chat%20p_1%7D%7B2%7D%5Cleft(1-%5Cfrac%7B%5Chat%20p_0+%20%5Chat%20p_1%7D%7B2%7D%5Cright)%0A%5Capprox%20(%5Chat%20p_0(1-%5Chat%20p_0))%20%5Capprox%20(%5Chat%20p_1(1-%5Chat%20p_1)).%0A"></p>
<p>Therefore,</p>
<p><img src="https://latex.codecogs.com/png.latex?%0An%5Capprox%5Cfrac%7B2%5Ctimes%5Cfrac%7B%5Chat%20p_0+%20%5Chat%20p_1%7D%7B2%7D(1-%5Cfrac%7B%5Chat%20p_0+%20%5Chat%20p_1%7D%7B2%7D)%5Cleft(z_%5Calpha%0A+%20z_%7B1-%5Cbeta%7D%0A%5Cright)%5E2%7D%0A%7B%5Cdelta%5E2%7D%20=%20%5Cfrac%7B2%5Ctimes%5Cbar%20p(1-%5Cbar%20p)%5Cleft(z_%7B1-%5Calpha%7D+%20z_%7B1-%5Cbeta%7D%0A%5Cright)%5E2%7D%0A%7B%5Cdelta%5E2%7D.%0A"></p>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>A/B Testing</category>
  <category>Hypothesis Testing</category>
  <category>Sample Size</category>
  <guid>https://yanghaowang.github.io/posts/sample-size-ab-testing/</guid>
  <pubDate>Wed, 31 Aug 2022 05:12:20 GMT</pubDate>
</item>
<item>
  <title>Noncompliance and LATE/CACE</title>
  <link>https://yanghaowang.github.io/posts/noncompliance-late-cace/</link>
  <description><![CDATA[ 






<section id="confounding" class="level3">
<h3 class="anchored" data-anchor-id="confounding">Confounding</h3>
<p><img src="https://yanghaowang.github.io/posts/noncompliance-late-cace/confounding1.png" class="img-fluid"></p>
<p>Classic confounding situation: X affects treatment A and affects outcome Y</p>
<ul>
<li><p><strong>If X is observed</strong>, we can analyze data using: <em>Matching</em>, <em>Propensity Score Matching</em>, and <em>IPTW</em></p></li>
<li><p>Even if there are risk factors, V, it is valid to simply control for X</p></li>
</ul>
<p><img src="https://yanghaowang.github.io/posts/noncompliance-late-cace/confounding2.png" class="img-fluid"></p>
<p>Suppose there are unmeasured/unobserved variables, U, that affect A and Y. Then we have <strong>unmeasured confounding</strong>.</p>
<ul>
<li><p>Ignorability assumption violated: <img src="https://latex.codecogs.com/png.latex?Y%5E1,Y%5E0%5Cnot%5Cperp%20A%5Cmid%20X"></p></li>
<li><p>Given X, we cannot obtain a valid matching sample (pseudo-population)</p></li>
</ul>
</section>
<section id="instrument-variables" class="level3">
<h3 class="anchored" data-anchor-id="instrument-variables">Instrument Variables</h3>
<p>The instrument variables (IV) approach is an alternative causal inference method that does not rely on the ignorability assumption.</p>
<p><img src="https://yanghaowang.github.io/posts/noncompliance-late-cace/iv.png" class="img-fluid"></p>
<section id="encouragement-design" class="level4">
<h4 class="anchored" data-anchor-id="encouragement-design">Encouragement Design</h4>
<p>A: Smoking during Pregnancy (yes/no)</p>
<p>Y: Birth Weight</p>
<p>X: Parity, Mother’s Age, Weight, etc.</p>
<p>Z: Randomize to either receive encouragement to stop smoking (Z=1) or receive usual care (Z=0)</p>
<blockquote class="blockquote">
<p>The encouragement will not affect the baby’s birth weight through any path other than stopping smoking.</p>
</blockquote>
<ul>
<li><p><strong>Intention-to-treat</strong> Analysis: Focus on the causal effect of encouragement</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%7B%5Crm%20E%7D%5Cleft(Y%5E%7BZ=1%7D%5Cright)%20-%20%7B%5Crm%20E%7D%5Cleft(Y%5E%7BZ=0%7D%5Cright)%0A"></p>
<p>Note it is NOT a causal effect of smoking.</p></li>
</ul>
</section>
</section>
<section id="randomized-trials-with-noncompliance" class="level3">
<h3 class="anchored" data-anchor-id="randomized-trials-with-noncompliance">Randomized Trials with Noncompliance</h3>
<p>Randomize Trial</p>
<p>Z: randomization to treatment (1 if randomized to treatment, 0 otherwise)</p>
<p>A: treatment received (1 if receive treatment, 0 otherwise)</p>
<p>Y: outcome</p>
<ul>
<li><p>Typically, NOT everyone assigned treatment will receive the treatment (e.g., Non-compliance)</p></li>
<li><p>Non-compliance makes a randomized trial like an observational study</p></li>
<li><p>Every subject will be assigned treatment Z and received treatment A.</p></li>
<li><p>Every subject has two potential values of treatment:</p>
<ul>
<li><p><img src="https://latex.codecogs.com/png.latex?A%5E%7BZ=0%7D=A%5E0">: It could be treatment (i.e., <img src="https://latex.codecogs.com/png.latex?A%5E0=1">) or no treatment (i.e.,<img src="https://latex.codecogs.com/png.latex?A%5E0=0">). It is the value of treatment if randomized to Z=0.</p></li>
<li><p><img src="https://latex.codecogs.com/png.latex?A%5E%7BZ=1%7D=A%5E1">: It could be treatment or no treatment. It is the value of treatment if randomized to Z=1.</p></li>
</ul></li>
<li><p>The <strong>average causal effect</strong> of <mark>treatment assignment on treatment received</mark>:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%7B%5Crm%20E%7D(A%5E%7BZ=1%7D-A%5E%7BZ=0%7D)%0A"></p>
<ul>
<li><p>Estimable from the observed data:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%7B%5Crm%20E%7D(A%5E%7BZ=z%7D)=%7B%5Crm%20E%7D(A%5Cmid%20Z=z),%5Cforall%20z%5Cin%20%5C%7B0,1%5C%7D.%0A"></p></li>
</ul></li>
<li><p>The <strong>average causal effect</strong> of treatment assignment on the outcome:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%7B%5Crm%20E%7D(Y%5E%7BZ=1%7D-Y%5E%7BZ=0%7D)%0A"></p>
<ul>
<li><p>This is the average value of the outcome if everyone had been assigned to receive treatment minus the average outcome if no one had been assigned to receive the treatment.</p>
<ul>
<li><p>It is the intention-to-treat effect.</p></li>
<li><p><strong>If perfect compliance</strong>, it would be equal to the causal effect of treatment.</p></li>
</ul></li>
<li><p>Estimable from the observed data:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%7B%5Crm%20E%7D(Y%5E%7BZ=z%7D)=%7B%5Crm%20E%7D(Y%5Cmid%20Z=z),%5Cforall%20z%5Cin%20%5C%7B0,1%5C%7D.%0A"></p></li>
</ul></li>
</ul>
</section>
<section id="compliance-classes" class="level3">
<h3 class="anchored" data-anchor-id="compliance-classes">Compliance Classes</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 5%">
<col style="width: 5%">
<col style="width: 13%">
<col style="width: 76%">
</colgroup>
<thead>
<tr class="header">
<th><img src="https://latex.codecogs.com/png.latex?A%5E0"></th>
<th><img src="https://latex.codecogs.com/png.latex?A%5E1"></th>
<th>Label</th>
<th>Implication</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>0</td>
<td>0</td>
<td>Never-takers</td>
<td>No variation in treatment received&nbsp;<br>and no information about causality</td>
</tr>
<tr class="even">
<td>0</td>
<td>1</td>
<td>Compliers</td>
<td>Treatment received is randomized <br>by design. Hope we can learn something.</td>
</tr>
<tr class="odd">
<td>1</td>
<td>0</td>
<td>Defiers</td>
<td>Assume this subpopulation is small <br>or does not exist.</td>
</tr>
<tr class="even">
<td>1</td>
<td>1</td>
<td>Always-takers</td>
<td>No variation in treatment received&nbsp;<br>and no information about causality</td>
</tr>
</tbody>
</table>
<section id="causal-effects" class="level4">
<h4 class="anchored" data-anchor-id="causal-effects">Causal Effects</h4>
<p>A motivation for using IV methods is concern about possible unmeasured confounding.</p>
<ul>
<li><p>If there is unmeasured confounding, we cannot marginalize over alll confounders via matching, IPTW, etc.</p>
<blockquote class="blockquote">
<p>Both matching and IPTW create a balanced sample or pseudo-population to measure the causal effect averaged over the whole population.</p>
</blockquote></li>
</ul>
<p>IV methods do not focus on the average causal effect for the population. They focus on a <strong>local average treatment effect</strong> (LATE) evaluated from a subpopulation of compliers.</p>
<ul>
<li>It is also known as the complier average causal effect (CACE).</li>
</ul>
</section>
<section id="observed-data" class="level4">
<h4 class="anchored" data-anchor-id="observed-data">Observed Data</h4>
<table class="caption-top table">
<thead>
<tr class="header">
<th><img src="https://latex.codecogs.com/png.latex?Z"></th>
<th><img src="https://latex.codecogs.com/png.latex?A"></th>
<th><img src="https://latex.codecogs.com/png.latex?A%5E%7BZ=0%7D"></th>
<th><img src="https://latex.codecogs.com/png.latex?A%5E%7BZ=1%7D"></th>
<th>Class</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>0</td>
<td>0</td>
<td>0</td>
<td>?</td>
<td>Never-takers or Compliers</td>
</tr>
<tr class="even">
<td>0</td>
<td>1</td>
<td>1</td>
<td>?</td>
<td>Always-takers or Defiers</td>
</tr>
<tr class="odd">
<td>1</td>
<td>0</td>
<td>?</td>
<td>0</td>
<td>Never-takers or Defiers</td>
</tr>
<tr class="even">
<td>1</td>
<td>1</td>
<td>?</td>
<td>1</td>
<td>Always-takers or&nbsp;Compliers</td>
</tr>
</tbody>
</table>
<ul>
<li><p>Compliance classes are also known as <strong>principal strata</strong>, which are latent.</p></li>
<li><p>Without additional assumptions, we cannot identify each subject into one of four categories. We can only narrow it down to two categories, however.</p></li>
</ul>
</section>
</section>
<section id="monotonicity-assumption" class="level3">
<h3 class="anchored" data-anchor-id="monotonicity-assumption">Monotonicity Assumption</h3>
<p>A variable is an instrumental variable (IV) if</p>
<ol type="1">
<li><p>It is associated with the treatment;</p></li>
<li><p>It affects the outcome only through its effect on treatment (also known as the exclusion restriction).</p>
<ul>
<li><p>Randomization should not be affecting the outcome, except possibly through the impact that randomization had on what treatment somebody received.</p></li>
<li><p>A valid IV should not affect unmeasured confounders.</p></li>
</ul></li>
</ol>
<p>The <strong>monotonicity assumption</strong> is that there are no defiers.</p>
<ul>
<li><p>The probability of treatment should increase with more encouragement.</p></li>
<li><p>No one consistently does the opposite of what they are told.</p></li>
</ul>
<p>With this monotonicity assumption, now we have enough information to identify the causal effect among compliers. For observed data, we have</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th><img src="https://latex.codecogs.com/png.latex?Z"></th>
<th><img src="https://latex.codecogs.com/png.latex?A"></th>
<th><img src="https://latex.codecogs.com/png.latex?A%5E%7BZ=0%7D"></th>
<th><img src="https://latex.codecogs.com/png.latex?A%5E%7BZ=1%7D"></th>
<th>Class</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>0</td>
<td>0</td>
<td>0</td>
<td>?</td>
<td>Never-takers or Compliers</td>
</tr>
<tr class="even">
<td>0</td>
<td>1</td>
<td>1</td>
<td><del>?</del>=&gt;1</td>
<td>Always-takers <del>or Defiers</del></td>
</tr>
<tr class="odd">
<td>1</td>
<td>0</td>
<td><del>?</del>=&gt;0</td>
<td>0</td>
<td>Never-takers <del>or Defiers</del></td>
</tr>
<tr class="even">
<td>1</td>
<td>1</td>
<td>?</td>
<td>1</td>
<td>Always-takers or&nbsp;Compliers</td>
</tr>
</tbody>
</table>
</section>
<section id="causal-effect-identification-and-estimation" class="level3">
<h3 class="anchored" data-anchor-id="causal-effect-identification-and-estimation">Causal Effect Identification and Estimation</h3>
<p>Intention-to-treat effect:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%7B%5Crm%20E%7D(Y%5E%7BZ=1%7D-Y%5E%7BZ=0%7D)%20=%20%7B%5Crm%20E%7D(Y%5Cmid%20Z=1)-%7B%5Crm%20E%7D(Y%20%5Cmid%20Z=0)%0A"></p>
<p>where</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%7B%5Crm%20E%7D(Y%5Cmid%20Z=1)&amp;=%7B%5Crm%20E%7D(Y%5Cmid%20Z=1,%5Ctext%7Balways%20takers%7D)%5CPr(%5Ctext%7Balways%20takers%7D)%5C%5C%5C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20&amp;+%7B%5Crm%20E%7D(Y%5Cmid%20Z=1,%5Ctext%7Bnever%20takers%7D)%5CPr(%5Ctext%7Bnever%20takers%7D)%5C%5C%5C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20&amp;+%7B%5Crm%20E%7D(Y%5Cmid%20Z=1,%5Ctext%7Bcompliers%7D)%5CPr(%5Ctext%7Bcompliers%7D).%0A%5Cend%7Balign*%7D%0A"></p>
<p>Note: Among always takers and never takers, we can drop the condition on Z:</p>
<ul>
<li><p><img src="https://latex.codecogs.com/png.latex?%7B%5Crm%20E%7D(Y%5Cmid%20Z=1,%5Ctext%7Balways%20takers%7D)=%7B%5Crm%20E%7D(Y%5Cmid%20%5Ctext%7Balways%20takers%7D)"></p></li>
<li><p><img src="https://latex.codecogs.com/png.latex?%7B%5Crm%20E%7D(Y%5Cmid%20Z=1,%5Ctext%7Bnever%20takers%7D)=%7B%5Crm%20E%7D(Y%5Cmid%20%5Ctext%7Bnever%20takers%7D)"></p></li>
</ul>
<p>Then we can simplify <img src="https://latex.codecogs.com/png.latex?%7B%5Crm%20E%7D(Y%5Cmid%20Z=1)"> and <img src="https://latex.codecogs.com/png.latex?%7B%5Crm%20E%7D(Y%5Cmid%20Z=0)">:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%7B%5Crm%20E%7D(Y%5Cmid%20Z=1)&amp;=%7B%5Crm%20E%7D(Y%5Cmid%20%5Ctext%7Balways%20takers%7D)%5CPr(%5Ctext%7Balways%20takers%7D)%5C%5C%5C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20&amp;+%7B%5Crm%20E%7D(Y%5Cmid%20%5Ctext%7Bnever%20takers%7D)%5CPr(%5Ctext%7Bnever%20takers%7D)%5C%5C%5C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20&amp;+%7B%5Crm%20E%7D(Y%5Cmid%20Z=1,%5Ctext%7Bcompliers%7D)%5CPr(%5Ctext%7Bcompliers%7D)%0A%5Cend%7Balign*%7D%0A"></p>
<p>and</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%7B%5Crm%20E%7D(Y%5Cmid%20Z=0)&amp;=%7B%5Crm%20E%7D(Y%5Cmid%20%5Ctext%7Balways%20takers%7D)%5CPr(%5Ctext%7Balways%20takers%7D)%5C%5C%5C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20&amp;+%7B%5Crm%20E%7D(Y%5Cmid%20%5Ctext%7Bnever%20takers%7D)%5CPr(%5Ctext%7Bnever%20takers%7D)%5C%5C%5C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20&amp;+%7B%5Crm%20E%7D(Y%5Cmid%20Z=0,%5Ctext%7Bcompliers%7D)%5CPr(%5Ctext%7Bcompliers%7D).%0A%5Cend%7Balign*%7D%0A"></p>
<p>Therefore,</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%7B%5Crm%20E%7D(Y%5E%7BZ=1%7D-Y%5E%7BZ=0%7D)&amp;=%7B%5Crm%20E%7D(Y%5Cmid%20Z=1)-%7B%5Crm%20E%7D(Y%20%5Cmid%20Z=0)%5C%5C%5C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20&amp;=%7B%5Crm%20E%7D(Y%5Cmid%20Z=1,%5Ctext%7Bcompliers%7D)%5CPr(%5Ctext%7Bcompliers%7D)%5C%5C%5C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20&amp;-%7B%5Crm%20E%7D(Y%5Cmid%20Z=0,%5Ctext%7Bcompliers%7D)%5CPr(%5Ctext%7Bcompliers%7D),%0A%5Cend%7Balign*%7D%0A"></p>
<p>which implies</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D%0A%5Cfrac%7B%5Ctext%7BE%7D(Y%5Cmid%20Z=1)-%5Ctext%7BE%7D(Y%20%5Cmid%20Z=0)%7D%7B%5CPr(%5Ctext%7Bcompliers%7D)%7D%0A&amp;=%7B%5Crm%20E%7D(Y%5Cmid%20Z=1,%5Ctext%7Bcompliers%7D)-%7B%5Crm%20E%7D(Y%5Cmid%20Z=0,%5Ctext%7Bcompliers%7D)%5C%5C%5C%0A&amp;=%7B%5Crm%20E%7D(Y%5E%7BA=1%7D%5Cmid%20%5Ctext%7Bcompliers%7D)-%7B%5Crm%20E%7D(Y%5E%7BA=0%7D%5Cmid%20%5Ctext%7Bcompliers%7D)%5C%5C%5C%0A&amp;=%7B%5Crm%20CACE%7D.%0A%5Cend%7Balign*%7D%0A"></p>
<blockquote class="blockquote">
<p>For the second line of the equation, because Z was randomized and these subjects are compliers, randomizing Z can be referred to as randomizing A.</p>
</blockquote>
<p>Also, <img src="https://latex.codecogs.com/png.latex?%5CPr(%5Ctext%7Bcompliers%7D)=%7B%5Crm%20E%7D(A%5Cmid%20Z=1)-%7B%5Crm%20E%7D(A%5Cmid%20Z=0)">.</p>
<ul>
<li><p><img src="https://latex.codecogs.com/png.latex?%7B%5Crm%20E%7D(A%5Cmid%20Z=1)">: Proportion of people who are always takers or compliers</p></li>
<li><p><img src="https://latex.codecogs.com/png.latex?%7B%5Crm%20E%7D(A%5Cmid%20Z=0)">: Proportion of people who are always takers</p></li>
<li><p>The difference is the proportion of compliers</p></li>
</ul>
<p>As a result, we have</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Ctext%7BCACE%7D=%5Cfrac%7B%5Ctext%7BE%7D(Y%5Cmid%20Z=1)-%5Ctext%7BE%7D(Y%5Cmid%20Z=0)%7D%7B%5Ctext%7BE%7D(A%5Cmid%20Z=1)-%5Ctext%7BE%7D(A%5Cmid%20Z=0)%7D%5Cleft(=%5Cfrac%7B%5Ctext%7BIntention-to-treat%7D%7D%7B%5CPr(%5Ctext%7Bcompliers%7D)%7D%5Cright)%0A"></p>
<p>where the numerator is the IIT and the denominator is the causal effect of treatment assignment on the treatment received.</p>
<ul>
<li><p>If perfect compliance, CACE=ITT.</p></li>
<li><p>Denominator always between 0 and 1. Thus, CACE will be at least as large as ITT.</p>
<ul>
<li><strong>ITT is an underestimate of CACE</strong> because some people assigned to treatment did not take it.</li>
</ul></li>
</ul>
<section id="summary" class="level4">
<h4 class="anchored" data-anchor-id="summary">Summary</h4>
<ul>
<li><p>IV requires 2 key assumptions, the strongest of which is the exclusion restriction.</p></li>
<li><p>If one also makes the monotonicity assumption, then the complier average causal effect is identified.</p></li>
</ul>
</section>
</section>
<section id="sensitivity-analysis" class="level3">
<h3 class="anchored" data-anchor-id="sensitivity-analysis">Sensitivity Analysis</h3>
<p>Sensitivity analysis is developed for each of the IV assumptions:</p>
<ul>
<li><p>Exclusion Analysis: If Z does directly affect Y by an amount <img src="https://latex.codecogs.com/png.latex?%5Crho">, would my conclusions change?</p></li>
<li><p>Monotonicity: If the proportion of defiers was <img src="https://latex.codecogs.com/png.latex?%5Cpi">, would my conclusions change?</p></li>
</ul>
<p><mark>Reference</mark>: Baiocchi et al.&nbsp;(2014) “Tutorial in Biostatistics: Instrumental Variable Methods for Causal Inference.”</p>
</section>
<section id="weak-instruments" class="level3">
<h3 class="anchored" data-anchor-id="weak-instruments">Weak Instruments</h3>
<p>The strength of an IV is how well it predicts treatment received.</p>
<ul>
<li><p>A strong instrument is highly predictive of treatment.</p>
<ul>
<li>Encouragement greatly increases the probability of treatment</li>
</ul></li>
<li><p>A weak instrument is weakly predictive of treatment.</p>
<ul>
<li>Encouragement barely increases the probability of treatment</li>
</ul></li>
</ul>
<section id="strength-of-ivs" class="level4">
<h4 class="anchored" data-anchor-id="strength-of-ivs">Strength of IVs</h4>
<p>Estimate the proportion of compliers: <img src="https://latex.codecogs.com/png.latex?%7B%5Crm%20E%7D(A%5Cmid%20Z=1)-%7B%5Crm%20E%7D(A%5Cmid%20Z=0)"></p>
<ul>
<li><p>If this number is close to 1, it has a strong instrument;</p></li>
<li><p>If close to 0, it has a weak instrument.</p></li>
</ul>
<blockquote class="blockquote">
<p>This proportion implies an effective sample size.</p>
</blockquote>
<p>Suppose only 1% of the population are compliers. <em>This leads to very large variance estimates, resulting in unstable estimates of causal effects</em>. It would likely produce confidence intervals that are too wide to be useful.</p>
<p><strong>Strengthen Instrument</strong>: Near/far Matching</p>
<ul>
<li><p>Match so that covariates are similar but the instrument is very different</p></li>
<li><p>Reference: Baiocchi et al.&nbsp;(2012) “Near/far matching: a study design approach to instrumental variables.”</p></li>
</ul>


</section>
</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Causal</category>
  <category>Causal-IV</category>
  <category>Causal-CACE/LATE</category>
  <guid>https://yanghaowang.github.io/posts/noncompliance-late-cace/</guid>
  <pubDate>Sat, 23 Jul 2022 06:15:48 GMT</pubDate>
</item>
<item>
  <title>IPTW Estimator and Doubly Robust Estimator</title>
  <link>https://yanghaowang.github.io/posts/iptw-doubly-robust/</link>
  <description><![CDATA[ 






<section id="iptw-estimator" class="level3">
<h3 class="anchored" data-anchor-id="iptw-estimator">IPTW Estimator</h3>
<p>Under the assumption of exchangeability and positivity, we can estimate <img src="https://latex.codecogs.com/png.latex?%7B%5Crm%20E%7D(Y%5E1)"> as</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cfrac%7B%5Csum%5En_%7Bi=1%7DI(A_i=1)%5Cfrac%7BY_i%7D%7B%5Cpi_i%7D%7D%7B%5Csum%5En_%7Bi=1%7DI(A_i=1)%5Cfrac%7B1%7D%7B%5Cpi_i%7D%7D%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Cpi_i=%5CPr(A=1%5Cmid%20X_i)"> is the propensity score.</p>
<ul>
<li><p>Inverse Probability of Treatment Weighting (IPTW) uses the inverse of the probability of being treated as weight, that is, <img src="https://latex.codecogs.com/png.latex?1/%5Cpi_i"> for individual <img src="https://latex.codecogs.com/png.latex?i">.</p></li>
<li><p><strong>IPTW uses the weight to create a pseudo-population where the numbers of subjects in the treatment and control groups are balanced.</strong></p></li>
<li><p>The numerator <img src="https://latex.codecogs.com/png.latex?%5Csum%5En_%7Bi=1%7DI(A_i=1)%5Cfrac%7BY_i%7D%7B%5Cpi_i%7D"> is the sum of the Y’s in treated pseudo-population, while the denominator <img src="https://latex.codecogs.com/png.latex?%5Csum%5En_%7Bi=1%7DI(A_i=1)%5Cfrac%7B1%7D%7B%5Cpi_i%7D"> is the number of subjects in treated pseudo-population. Overall, we have the average value of the outcome if treated, i.e., <img src="https://latex.codecogs.com/png.latex?%7B%5Crm%20E%7D(Y%5E1)">.</p></li>
<li><p>Exchangeability is another way of saying ignorability given X.</p></li>
<li><p>Positivity suggests <img src="https://latex.codecogs.com/png.latex?%5Cpi_i%5Cin(0,1)"> which is critical for this formula since <img src="https://latex.codecogs.com/png.latex?%5Cpi_i"> is in the denominator position.</p></li>
</ul>
<p>Similarly, we can estimate <img src="https://latex.codecogs.com/png.latex?%7B%5Crm%20E%7D(Y%5E0)"> by</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cfrac%7B%5Csum%5En_%7Bi=1%7DI(A_i=0)%5Cfrac%7BY_i%7D%7B1-%5Cpi_i%7D%7D%7B%5Csum%5En_%7Bi=1%7DI(A_i=0)%5Cfrac%7B1%7D%7B1-%5Cpi_i%7D%7D.%0A"></p>
<p>Then, an average causal effect estimator is obtained by</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%7B%5Crm%20E%7D(Y%5E1)-%7B%5Crm%20E%7D(Y%5E0).%0A"></p>
</section>
<section id="large-weight-problem" class="level3">
<h3 class="anchored" data-anchor-id="large-weight-problem">Large Weight Problem</h3>
<p>When using IPTW estimation, the large weights can create a problem, i.e., large standard errors.</p>
<blockquote class="blockquote">
<ul>
<li><p>Imagine one person has a weight of 10000,&nbsp;which means this person represents 10,000 people. So much is riding on this one person. That creates noise in a sense.</p></li>
<li><p>[Further Intuition] We estimate the standard errors with bootstrapping. The value of our estimate in each of these bootstrap samples is going to depend a great deal on the inclusion/appearance of this one person. When this person is in, the parameter estimate will be pulled towards him, while when he is out, that is not going to happen. As a result, the parameter estimate is going to vary a lot in large part due to this one person.</p></li>
</ul>
</blockquote>
<p>Check the distribution of weights in plots.</p>
<ul>
<li><p>Density plot with tick marks on the bottom</p></li>
<li><p>Scatter plot for a sorted weight data series from the smallest to the largest</p></li>
</ul>
</section>
<section id="remedies-for-large-weights" class="level3">
<h3 class="anchored" data-anchor-id="remedies-for-large-weights">Remedies for Large Weights</h3>
<section id="trimming-the-tails" class="level4">
<h4 class="anchored" data-anchor-id="trimming-the-tails">Trimming the Tails</h4>
<ul>
<li><p>Large weights occur at observations in the tails of the propensity score distribution</p></li>
<li><p>Trimming the tails can eliminate some of the extreme weights</p>
<ul>
<li><p>A common strategy:</p>
<ul>
<li><p><em>Remove <strong>treated</strong> subjects</em> whose propensity scores are above <em>the 98th percentile from</em> the distribution among <strong><em>controls</em></strong></p></li>
<li><p><em>Remove <strong>control</strong> subjects</em> whose propensity scores are below <em>the 2nd percentile from</em> the distribution among <em><b>treated</b> subjects</em></p></li>
</ul></li>
</ul></li>
</ul>
</section>
<section id="weight-truncation" class="level4">
<h4 class="anchored" data-anchor-id="weight-truncation">Weight Truncation</h4>
<p>Truncation Steps:</p>
<ol type="1">
<li><p>Determine a maximum allowable weight</p>
<ul>
<li><p>Could be a specific value (e.g., 100)</p></li>
<li><p>Could be based on a percentile (e.g., 99th)</p></li>
</ul></li>
<li><p>If one weight is greater than the maximum allowable, set it to the maximum allowable value</p>
<ul>
<li>For example, if your upper limit is 100, someone who weights 1000 will be set to 100 instead.</li>
</ul></li>
</ol>
<p>Truncation changes the data and hence introduces bias. So there involves a bias-variance trade-off:</p>
<ul>
<li><p>Truncation: Bias, smaller variance</p></li>
<li><p>No Truncation: Unbiased, larger variance</p></li>
</ul>
<p>Judge if the trade-off&nbsp;is worth based on the mean squared error. If truncating a small number of observations (not too&nbsp;many) that have extreme weights, you’ll probably be better off in terms of mean squared error.</p>
</section>
</section>
<section id="doubly-robust-estimators" class="level3">
<h3 class="anchored" data-anchor-id="doubly-robust-estimators">Doubly Robust Estimators</h3>
<ul>
<li><p>IPTW Estimator: We can estimate <img src="https://latex.codecogs.com/png.latex?%7B%5Crm%20E%7D(Y%5E1)"> given by</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cfrac%7B1%7D%7Bn%7D%5Csum_%7Bi=1%7D%5En%5Cfrac%7BA_iY_i%7D%7B%5Cpi_i(X_i)%7D,%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Cpi_i(X_i)"> is the propensity score. This estimator is unbiased if <img src="https://latex.codecogs.com/png.latex?%5Cpi_i(X_i)"> is correctly specified.</p>
<ul>
<li><p><img src="https://latex.codecogs.com/png.latex?%5Csum_%7Bi=1%7D%5En%20A_i"> counts the number of treated subjects.</p></li>
<li><p><img src="https://latex.codecogs.com/png.latex?1/%5Cpi_i(X_i)"> is <strong>the weight used to constructing a pseudo-population</strong>. For example, there are 9 out of 10 subjects treated in a randomized trial. The total number <img src="https://latex.codecogs.com/png.latex?n"> of subjects is 10 and the propensity score <img src="https://latex.codecogs.com/png.latex?%5Cpi_i"> is 0.9 for any <img src="https://latex.codecogs.com/png.latex?i">. The IPTW estimator gives an expectation of <img src="https://latex.codecogs.com/png.latex?Y%5E1">.</p></li>
</ul></li>
<li><p>Regression-based Estimator: We can estimate <img src="https://latex.codecogs.com/png.latex?%7B%5Crm%20E%7D(Y%5E1)"> given by</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cfrac%7B1%7D%7Bn%7D%5Csum_%7Bi=1%7D%5En%5Cleft%5C%7BA_iY_i+(1-A_i)m_1(X_i)%5Cright%5C%7D%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?m_1(X)=%7B%5Crm%20E%7D(Y%5Cmid%20A=1,X)">.</p>
<ul>
<li>Instead of creating a pseudo-population, we use <img src="https://latex.codecogs.com/png.latex?m_1(X_i)"> to predict the value of <img src="https://latex.codecogs.com/png.latex?Y%5E1"> for subjects who are not treated.</li>
</ul></li>
<li><p>Doubly Robust Estimator: It is an unbiased estimator if either the propensity score model or the outcome regression model are correctly specified.</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cfrac%7B1%7D%7Bn%7D%5Csum_%7Bi=1%7D%5En%5CBigg%5C%7B%5Cunderbrace%7B%0A%5Cfrac%7BA_iY_i%7D%7B%5Cpi_i(X_i)%7D%7D_%7B%5Crm%20IPTW%7D%0A-%5Cunderbrace%7B%0A%5Cfrac%7BA_i-%5Cpi_i(X_i)%7D%7B%5Cpi_i(X_i)%7Dm_1(X_i)%7D_%7B%5Crm%20Augmentation%7D%5CBigg%5C%7D%0A"></p>
<p>This doubly robust estimator is also known as <strong>Augmented IPTW</strong> (AIPTW) estimators. In general, AIPTW estimators should be <em>more efficient</em> than regular IPTW estimators.</p></li>
</ul>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Causal</category>
  <category>Causal-IPW</category>
  <category>Causal-DoublyRobust</category>
  <guid>https://yanghaowang.github.io/posts/iptw-doubly-robust/</guid>
  <pubDate>Sun, 17 Jul 2022 05:53:12 GMT</pubDate>
</item>
<item>
  <title>Greedy Matching and Propensity Score Matching</title>
  <link>https://yanghaowang.github.io/posts/greedy-propensity-matching/</link>
  <description><![CDATA[ 






<section id="greedy-nearest-neighbor-matching" class="level3">
<h3 class="anchored" data-anchor-id="greedy-nearest-neighbor-matching">Greedy (Nearest-neighbor) Matching</h3>
<section id="pair-matching" class="level4">
<h4 class="anchored" data-anchor-id="pair-matching">Pair Matching</h4>
<p>Steps:</p>
<ol type="1">
<li><p>Randomly order list of treated subjects and control subjects</p></li>
<li><p>Start with the first treated subject. Match to the control with the smallest distance (this is greedy).</p></li>
<li><p>Remove the matched control from the list of available matches.</p></li>
<li><p>Move on to the next treated subject. Match to the control with the smallest distance.</p></li>
<li><p>Repeat steps 3 and 4 until you have matched all treated subjects.</p></li>
</ol>
<table class="caption-top table">
<colgroup>
<col style="width: 47%">
<col style="width: 52%">
</colgroup>
<thead>
<tr class="header">
<th>Advantage</th>
<th>Disadvantage</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>1.&nbsp;Intuitive <br>2. Computationally fast<br>- Involves a series of simple algorithms (identifying minimum distance)<br>- Fast even for large data sets<br>- R package: MatchIt</td>
<td>1. Not invariant to initial order of list <br>2. Not optimal<br>- Always taking the smallest distance match does not minimize total distance<br>-Can lead to some bad matches (think of step3 above)</td>
</tr>
</tbody>
</table>
</section>
<section id="many-to-one-matching" class="level4">
<h4 class="anchored" data-anchor-id="many-to-one-matching">Many-to-one Matching</h4>
<p>For k:1 matching: After everyone has 1 match, go through the list again and find 2nd matches. Repeat until k matches.</p>
<table class="caption-top table">
<colgroup>
<col style="width: 29%">
<col style="width: 70%">
</colgroup>
<thead>
<tr class="header">
<th>Advantage</th>
<th>Disadvantage</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>End up&nbsp;<em>using more of the controls and a large sample size</em>. It suggests a more efficient estimate of the causal effect.</td>
<td>Adding a new treated subject to your data set&nbsp;would be more of an efficiency gain than adding another control to a matched set. So there is some power gain, some efficiency gain, but it’s not very large. The many-to-one matching should lead to <em>a little more bias, but smaller variance</em>.</td>
</tr>
</tbody>
</table>
</section>
<section id="caliper" class="level4">
<h4 class="anchored" data-anchor-id="caliper">Caliper</h4>
<p>A bad match can be defined using a <em>caliper</em> - maximum acceptable distance.</p>
<ul>
<li><p>Only match a treated subject if the best match has a distance less than the caliper</p></li>
<li><p>Recall <em>positivity assumption</em>: Probability of each treatment given X should be non-zero, i.e., <img src="https://latex.codecogs.com/png.latex?%5CPr(T%5Cmid%20X)%5Cin(0,1)%5Cspace%5Cforall%20X">.</p>
<ul>
<li><p>If no matches within the caliper, it is a sign that the positivity assumption would be violated</p></li>
<li><p>Excluding these subjects makes the assumption more realistic</p></li>
<li><p>Drawback: Hard to define</p></li>
</ul></li>
</ul>
</section>
</section>
<section id="optimal-matching" class="level3">
<h3 class="anchored" data-anchor-id="optimal-matching">Optimal Matching</h3>
<ul>
<li><p>Minimize global distance (i.e., total distance)</p>
<ul>
<li>Greedy matching&nbsp;is not necessarily optimal and usually is not in terms of minimizing the total distance. Because there might be times when you want to save a match for&nbsp;a later subject and accept a slightly less good match now.</li>
</ul></li>
<li><p>Computationally demanding</p>
<ul>
<li>R packages: <code>optmatch</code>, <code>rcbalance</code></li>
</ul></li>
</ul>
</section>
<section id="balance-assessment" class="level3">
<h3 class="anchored" data-anchor-id="balance-assessment">Balance Assessment</h3>
<ul>
<li><p>Covariate Balance</p>
<ul>
<li><p><em>Two sample t-tests</em> for continuous variables or <em>Chi-sqaure tests</em> for discrete variables</p>
<ul>
<li><p>Two sample t-test (equal variance)</p>
<p><img src="https://latex.codecogs.com/png.latex?%0At=%5Cfrac%7B%5Cbar%20X_1-%5Cbar%20X_2%7D%7Bs_p%5Csqrt%7B1/n_1+1/n_2%7D%7D%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?n_1"> and <img src="https://latex.codecogs.com/png.latex?n_2"> are sample sizes, <img src="https://latex.codecogs.com/png.latex?s_p"> is the population deviation such that</p>
<p><img src="https://latex.codecogs.com/png.latex?%0As_p%5E2=%5Cfrac%7B(n_1-1)s_1%5E2+(n_2-1)s%5E2_2%7D%7Bn_1+n_2-2%7D.%0A"></p>
<blockquote class="blockquote">
<p>When <img src="https://latex.codecogs.com/png.latex?n_1=n_2">, <img src="https://latex.codecogs.com/png.latex?s_p"> reduces to <img src="https://latex.codecogs.com/png.latex?(s%5E2_1+s%5E2_2)/2">.</p>
</blockquote></li>
<li><p>Two sample t-test (unequal variance)</p>
<p><img src="https://latex.codecogs.com/png.latex?%0At=%5Cfrac%7B%5Cbar%20X_1-%5Cbar%20X_2%7D%7B%5Csqrt%7Bs%5E2_1/n_1+s%5E2_2/n_2%7D%7D%0A"></p></li>
<li><p><a href="https://www.jmp.com/en_us/statistics-knowledge-portal/chi-square-test/chi-square-test-of-independence.html">Chi-Square Test of Independence | Introduction to Statistics | JMP</a></p></li>
<li><p><a href="https://www.jmp.com/en_us/statistics-knowledge-portal/chi-square-test/chi-square-goodness-of-fit-test.html">Chi-Square Goodness of Fit Test | Introduction to Statistics | JMP</a></p></li>
</ul></li>
<li><p>Drawback: p-values are dependent on the sample size. Particularly, small differences in means can be significant with a small p-value if the sample size is large. This is what we don’t want.</p>
<p><img src="https://latex.codecogs.com/png.latex?%0Asmd=%5Cfrac%7B%5Cbar%7BX%7D_%5Ctext%7Btreatment%7D-%5Cbar%20X_%5Ctext%7Bcontrol%7D%7D%0A%7B%5Csqrt%7B%5Cfrac%7Bs%5E2_%5Ctext%7Btreatment%7D+s%5E2_%5Ctext%7Bcontrol%7D%7D%7B2%7D%7D%7D%0A"></p></li>
<li><p>Standardized (mean) differences</p>
<p><img src="https://latex.codecogs.com/png.latex?%0Asmd=%5Cfrac%7B%5Cbar%7BX%7D_%5Ctext%7Btreatment%7D-%5Cbar%20X_%5Ctext%7Bcontrol%7D%7D%0A%7B%5Csqrt%7B%5Cfrac%7Bs%5E2_%5Ctext%7Btreatment%7D+s%5E2_%5Ctext%7Bcontrol%7D%7D%7B2%7D%7D%7D%0A"></p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Values</th>
<th>Balance</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>&lt;0.1</td>
<td>Adequate balance</td>
</tr>
<tr class="even">
<td>0.1-0.2</td>
<td>Not too alarming</td>
</tr>
<tr class="odd">
<td>&gt;0.2</td>
<td>Serious imbalance</td>
</tr>
</tbody>
</table></li>
</ul></li>
</ul>
</section>
<section id="randomization-tests" class="level3">
<h3 class="anchored" data-anchor-id="randomization-tests">Randomization Tests</h3>
<p>Also known as <strong>Permutation Tests</strong> and <strong>Exact Tests</strong></p>
<p>Test Steps:</p>
<ol type="1">
<li><p>Compute the test statistic from observed data</p></li>
<li><p>Assume the null hypothesis of no treatment effect is true</p></li>
<li><p>Randomly permute treatment assignment <em>within pairs</em> and re-compute test statistic</p></li>
<li><p>Repeat many times and see how unusual the observed statistic is</p></li>
</ol>
<p>Notes:</p>
<ul>
<li><p>When calculating a p-value, the intuition is to calculate the probability of something as extreme or more extreme than our particular value</p></li>
<li><p>This test is equivalent to the McNemar test for paired binary/discrete data and equivalent to paired t-test for paired continuous data</p></li>
</ul>
</section>
<section id="sensitivity-analysis" class="level3">
<h3 class="anchored" data-anchor-id="sensitivity-analysis">Sensitivity Analysis</h3>
<ul>
<li><p>Overt bias could occur if there was imbalance on observed covariates</p></li>
<li><p>There is no guarantee that matching will result in balance on variables that we did not match on (including unobserved variabels)</p>
<ul>
<li><p>If these unobserved variables are confounders. then we have hidden bias and ignorability assumption violated (i.e., <img src="https://latex.codecogs.com/png.latex?Y_0,Y_1%5Cperp%20T%5Cmid%20X">)</p>
<blockquote class="blockquote">
<p>Understanding of Ignorability: <img src="https://latex.codecogs.com/png.latex?Y=Y_0+(Y_1-Y_0)%5Ctimes%20T"> where <img src="https://latex.codecogs.com/png.latex?T=1"> if treated, 0 otherwise. Ignorability says <img src="https://latex.codecogs.com/png.latex?T"> certainly affects observed outcome <img src="https://latex.codecogs.com/png.latex?Y"> by defination but does not relate to the values of <img src="https://latex.codecogs.com/png.latex?Y_0"> and <img src="https://latex.codecogs.com/png.latex?Y_1">.</p>
<p>Reference: <a href="https://stats.stackexchange.com/questions/474616/strong-ignorability-confusion-on-the-relationship-between-outcomes-and-treatmen/474619#474619">causality - Strong ignorability: confusion on the relationship between outcomes and treatment - Cross Validated</a></p>
</blockquote></li>
</ul></li>
</ul>
<section id="motivation" class="level4">
<h4 class="anchored" data-anchor-id="motivation">Motivation</h4>
<p>If there is hidden bias, how severe it would have to be to change conclusions.</p>
<ul>
<li><p>Let <img src="https://latex.codecogs.com/png.latex?%5Cpi_j"> and <img src="https://latex.codecogs.com/png.latex?%5Cpi_k"> be the probability that person <img src="https://latex.codecogs.com/png.latex?j"> and <img src="https://latex.codecogs.com/png.latex?k"> receive treatment</p></li>
<li><p>Suppose person <img src="https://latex.codecogs.com/png.latex?j"> and <img src="https://latex.codecogs.com/png.latex?k"> are perfectly matched so that their observed covariates <img src="https://latex.codecogs.com/png.latex?X_j"> and <img src="https://latex.codecogs.com/png.latex?X_k"> are the same.</p></li>
<li><p>Inequality</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cfrac%7B1%7D%7B%5CGamma%7D%5Cle%5Cfrac%7B%5Cfrac%7B%5Cpi_j%7D%7B1-%5Cpi_j%7D%7D%7B%5Cfrac%7B%5Cpi_k%7D%7B1-%5Cpi_k%7D%7D%5Cle%5CGamma%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5CGamma"> is odds ratio.</p>
<ul>
<li><p>If <img src="https://latex.codecogs.com/png.latex?%5Cpi_j=%5Cpi_k">, then <img src="https://latex.codecogs.com/png.latex?%5CGamma=1">, suggesting no hidden bias</p></li>
<li><p><img src="https://latex.codecogs.com/png.latex?%5CGamma%3E1"> implies hidden bias</p></li>
<li><p><img src="https://latex.codecogs.com/png.latex?%5Cfrac%7B%5Cpi_j%7D%7B1-%5Cpi_j%7D"> is the odds of treatment for person <img src="https://latex.codecogs.com/png.latex?j"></p></li>
</ul></li>
</ul>
</section>
</section>
<section id="propensity-score" class="level3">
<h3 class="anchored" data-anchor-id="propensity-score">Propensity Score</h3>
<p>The propensity score is the probability of receiving treatment rather than control, given covariates X:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cpi_i=%5CPr(A=1%5Cmid%20X)%20%5Ctext%7B%20where%20%7DA=1%20%5Ctext%7B%20for%20treatment%20and%200%20for%20control.%7D%0A"></p>
<section id="balancing-score" class="level4">
<h4 class="anchored" data-anchor-id="balancing-score">Balancing Score</h4>
<p>Formally,</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5CPr(X=x%5Cmid%20%5Cpi(X)=p,A=1)=%5CPr(X=x%5Cmid%20%5Cpi(X)=p,A=0)%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5CPr(X=x)"> represents the distributions of covariates <img src="https://latex.codecogs.com/png.latex?X"> at every value <img src="https://latex.codecogs.com/png.latex?x"> and the propensity score function <img src="https://latex.codecogs.com/png.latex?%5Cpi(X)"> generates the value of <img src="https://latex.codecogs.com/png.latex?p">.</p>
<p>Implication: If we match according to the propensity score, we should achieve balance.</p>
</section>
<section id="estimated-propensity-score" class="level4">
<h4 class="anchored" data-anchor-id="estimated-propensity-score">Estimated Propensity Score</h4>
<p>Estimate <img src="https://latex.codecogs.com/png.latex?%5CPr(A=1%5Cmid%20X)"> to obtain <img src="https://latex.codecogs.com/png.latex?%5Chat%20p"></p>
<ul>
<li><p>The outcome is A, which is binary</p></li>
<li><p>Estimate the propensity score using logistic regression</p>
<ol type="1">
<li><p>Fit a logistic regression model: outcome A and covariates X</p></li>
<li><p>From that model, get the predicted probability (fitted value) for each subject, which is the estimated propensity score, <img src="https://latex.codecogs.com/png.latex?%5Chat%20p"></p></li>
</ol></li>
</ul>
<blockquote class="blockquote">
<p>In the randomized control trials, the propensity score is 0.5 by design, since given X subjects are randomly assigned to the treatment or the control group.</p>
</blockquote>
</section>
</section>
<section id="propensity-score-matching" class="level3">
<h3 class="anchored" data-anchor-id="propensity-score-matching">Propensity Score Matching</h3>
<p>The propensity score is a scalar. The matching problem is simplified, in that we are only matching on one variable.</p>
<section id="trimming-tails" class="level4">
<h4 class="anchored" data-anchor-id="trimming-tails">Trimming Tails</h4>
<p>Remove subjects who have extreme values of the propensity scores</p>
<ul>
<li><p>Control subjects whose propensity score is less than the minimum in the treatment group</p></li>
<li><p>Treated subjects whose propensity score is greater than the maximum in the control group</p></li>
</ul>
<p>Trimming the tails makes the positivity assumption more reasonable and prevents extrapolation.</p>
</section>
<section id="matching" class="level4">
<h4 class="anchored" data-anchor-id="matching">Matching</h4>
<p>Compute a distance between the propensity score for each treated subject with every control. Then use the nearest neighbor (i.e., greedy mathcing) or optimal matching as before.</p>
<p>In practice, <strong>logit (log-odds) of the propensity score is often used</strong>, rather than the propensity score itself.</p>
<ul>
<li><p>The propensity score is bounded between 0 and 1, making many values similar</p></li>
<li><p>Logit of the propensity score is unbounded – this transformation essentially <strong>stretches the distribution, while preserving ranks</strong>.</p></li>
<li><p>Match on <img src="https://latex.codecogs.com/png.latex?%7B%5Crm%20logit%7D(%5Cpi)=%5Clog(%5Cpi/(1-%5Cpi))"> rather than <img src="https://latex.codecogs.com/png.latex?%5Cpi"></p></li>
</ul>
</section>
<section id="caliper-1" class="level4">
<h4 class="anchored" data-anchor-id="caliper-1">Caliper</h4>
<p>In practice, a common choice for a caliper (i.e., <em>the maximum distance we are willing to tolerate in matching</em>) is 0.2 times the standard deviation of the logit of the propensity score.</p>
<ol type="1">
<li><p>Estimate the propensity score using logistic regression</p></li>
<li><p>logit-transform the propensity score</p></li>
<li><p>Take the standard deviation of this transformed variable</p></li>
<li><p>Set the caliper to 0.2 times the value from step 3</p></li>
</ol>
<blockquote class="blockquote">
<p>A smaller caliper suggests less bias but more variance.</p>
</blockquote>
</section>
<section id="post-matching" class="level4">
<h4 class="anchored" data-anchor-id="post-matching">Post-matching</h4>
<p>The outcome analysis methods can be the same as those that would be used if matching directly on covariates. For example,</p>
<ul>
<li><p>Randomization tests</p></li>
<li><p>Conditional logistic regression, GEE, Stratified Cox Model</p></li>
</ul>


</section>
</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Causal</category>
  <category>Causal-Matching</category>
  <guid>https://yanghaowang.github.io/posts/greedy-propensity-matching/</guid>
  <pubDate>Sat, 09 Jul 2022 20:28:39 GMT</pubDate>
</item>
<item>
  <title>Observational Studies and Matching Overview</title>
  <link>https://yanghaowang.github.io/posts/observational-matching-overview/</link>
  <description><![CDATA[ 






<section id="observational-studies" class="level3">
<h3 class="anchored" data-anchor-id="observational-studies">Observational Studies</h3>
<section id="randomized-trials" class="level4">
<h4 class="anchored" data-anchor-id="randomized-trials">Randomized Trials</h4>
<ul>
<li><p>Treatment assignment A would be determined by a fair coin flip <img src="https://yanghaowang.github.io/posts/observational-matching-overview/RTC.png" class="img-fluid"></p></li>
<li><p>No backdoor path from A to Y</p></li>
<li><p>Distributions of pre-treatment variables X that affect Y are the same in both treatment groups (covariate balance)</p></li>
</ul>
<p>Thus, if the outcome distribution ends up differing, it will not be attributable to differences in X.</p>
</section>
<section id="why-not-always-randomize" class="level4">
<h4 class="anchored" data-anchor-id="why-not-always-randomize">Why not always randomize?</h4>
<ul>
<li><p>Randomized trials are expensive.</p></li>
<li><p>Randomizing treatment/exposure is unethical.</p></li>
<li><p>Some (many) people will refuse to participate in trials.</p></li>
<li><p>Randomized trials take time (you have to wait for outcome data). In some cases, by the time you have outcome data, the question might no longer be relevant.</p></li>
</ul>
</section>
<section id="observational-studies-1" class="level4">
<h4 class="anchored" data-anchor-id="observational-studies-1">Observational Studies</h4>
<ul>
<li><p>Data Collection Types:</p>
<ul>
<li><p>Planned, prospective, active data collection</p></li>
<li><p>Databases, retrospective, passive data collection</p></li>
</ul></li>
<li><p>In observational studies, the distribution of X will differ between treatment groups</p></li>
</ul>
</section>
</section>
<section id="overview-of-matching" class="level3">
<h3 class="anchored" data-anchor-id="overview-of-matching">Overview of Matching</h3>
<section id="matching" class="level4">
<h4 class="anchored" data-anchor-id="matching">Matching</h4>
<p>Matching is a method that attempts to make an observational study more like a randomized trial.</p>
<ul>
<li><p>Controlling for confounders is achieved at the design phase without looking at the outcome. In other words, matching is similar to randomized control trials (RCT) that we are blind to the outcomes.</p></li>
<li><p>Matching reveals the lack of overlap in covariate distribution.</p></li>
<li><p>Once matched, data are treated as if from a randomized trial.</p></li>
</ul>
</section>
<section id="stochastic-balance" class="level4">
<h4 class="anchored" data-anchor-id="stochastic-balance">Stochastic Balance</h4>
<p>In a randomized trial, treated and control subjects are not perfectly matched. The distribution of covariates, however, is balanced between groups, which we call <em>stochastic balance</em>.</p>
<ul>
<li><p>Matching on covariates can achieve stochastic balance.</p></li>
<li><p>We start with the treated group and make the distribution of covariates in the control population look like that in the treated population.</p>
<ul>
<li>The estimate from this procedure is a <em>causal effect of treatment on the treated</em>.</li>
</ul></li>
<li><p>In matching, we <em>typically</em> focus on the causal effect of treatment on the treated, because we find matches for each treated person from the control population. So what we are making inferences about is the treated population.</p>
<ul>
<li>We can do matching where we make the treated and the control populations not only look like each other but also look like the population as a whole. It involves more complicated techniques but is feasible.</li>
</ul></li>
</ul>
</section>
<section id="fine-balance" class="level4">
<h4 class="anchored" data-anchor-id="fine-balance">Fine Balance</h4>
<p>Sometimes we might be willing to accept some non-ideal matches if treated and control groups have the same distribution of covariates.</p>
<blockquote class="blockquote">
<p>[Example]</p>
<p>Match 1: treated, male, age 40 and control, female, age 45</p>
<p>Match 2: treated, female, age 45 and control, male, age 40</p>
<p>It is not an ideal match because the treated male and female are matched with the control female and male of different ages. We don’t achieve the stochastic balance. However, the overall average age and percentage of males are the same in both groups, even though neither match is great. This is considered a <strong>fine match</strong>.</p>
</blockquote>
<p>It’s always going to look for the best pairwise kind of matches,&nbsp;but we will tolerate some bad matches as long as we get a fine balance.</p>
</section>
<section id="number-of-matches" class="level4">
<h4 class="anchored" data-anchor-id="number-of-matches">Number of Matches</h4>
<ul>
<li><p>One-to-one (pair matching)</p></li>
<li><p>Many-to-one (k controls to every treated subject)</p></li>
<li><p>Mixed</p>
<ul>
<li><p>Sometimes match 1, sometimes more than 1, control to treated subjects</p></li>
<li><p>If multiple good matches are available, use them.</p></li>
</ul></li>
</ul>
</section>
</section>
<section id="matching-on-confounders" class="level3">
<h3 class="anchored" data-anchor-id="matching-on-confounders">Matching on Confounders</h3>
<p>In the matching, “distance” is a measure of how similar the values of confounders are for different people.</p>
<ul>
<li><p>Mahalanobis Distance</p>
<p><img src="https://latex.codecogs.com/png.latex?%0AD(X_i,X_j)=%5Csqrt%7B(X_i-X_j)%5ETS%5E%7B-1%7D(X_i-X_j)%7D%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?X_i=%5Bx_%7Bi1%7D,%5Cdots,x_%7BiK%7D%5D"> and <img src="https://latex.codecogs.com/png.latex?X_j=%5Bx_%7Bj1%7D,%5Cdots,x_%7BjK%7D%5D"> are K-by-1 vectors of K covariates for row <img src="https://latex.codecogs.com/png.latex?i"> and <img src="https://latex.codecogs.com/png.latex?j"> (i.e., individual <img src="https://latex.codecogs.com/png.latex?i"> and <img src="https://latex.codecogs.com/png.latex?j">) in data <img src="https://latex.codecogs.com/png.latex?X">, and <img src="https://latex.codecogs.com/png.latex?S=COV(X)"> is a K-by-K covariance matrix.</p>
<ul>
<li><p><img src="https://latex.codecogs.com/png.latex?S_%7Bkk'%7D=%7B%5Crm%20E%7D%5B(x%5Ek-%5Cbar%20x%5Ek)(x%5E%7Bk'%7D-%5Cbar%20x%5E%7Bk'%7D)%5D"> where <img src="https://latex.codecogs.com/png.latex?%5Cbar%20x%5Ek"> and <img src="https://latex.codecogs.com/png.latex?%5Cbar%20x%5E%7Bk'%7D"> are the sample means of covariate <img src="https://latex.codecogs.com/png.latex?k"> and <img src="https://latex.codecogs.com/png.latex?k'"> over <img src="https://latex.codecogs.com/png.latex?n"> observations.</p></li>
<li><p>In other words, M distance is the square root of the sum of squared distances between each covariate scaled by the covariance matrix.</p></li>
<li><p><a href="https://www.machinelearningplus.com/statistics/mahalanobis-distance/">Program Mahalanobis Distance in Python</a></p></li>
</ul></li>
<li><p>Robust Mahalanobis Distance</p>
<ul>
<li><p>Motivation</p>
<ul>
<li><p>Outliers can create large distances between subjects, even if the covariates are otherwise similar</p></li>
<li><p>The ranks might be more relevant</p>
<blockquote class="blockquote">
<p>[Example] Highest and second-highest ranked values of covariates perhaps should be treated as similar, even if the values are far apart.</p>
</blockquote></li>
</ul></li>
<li><p>Calculation</p>
<ul>
<li><p>Replace each covariate value with its rank</p></li>
<li><p>Constant diagonal on the covariance matrix</p></li>
<li><p>Calculate the usual Mahalanobis distance on the ranks</p></li>
</ul></li>
</ul></li>
</ul>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Causal</category>
  <category>Causal-Matching</category>
  <guid>https://yanghaowang.github.io/posts/observational-matching-overview/</guid>
  <pubDate>Fri, 08 Jul 2022 07:34:47 GMT</pubDate>
</item>
<item>
  <title>不一样的清明节</title>
  <link>https://yanghaowang.github.io/posts/my-different-qingming/</link>
  <description><![CDATA[ 






<p><em>This is a family memoir written by my father to my beloved grandpa.</em></p>
<section id="不一样的清明节" class="level1">
<h1>不一样的清明节</h1>
<p>——纪念父亲离世一周年</p>
<p>今年的清明日，刚好是父亲离开我们一周年的日子，也是计划上我们兄妹五人为父亲第一次做清明的日子。可是计划不如变化快，近期全国各地新冠疫情似乎更加严重了，南昌、婺源都有零星病例，我们兄妹五人也因此不能返乡。没想到去年清明节在卧榻旁的守候，竟成了我们最后的相处时光。回想年少时和成年后的过往，记忆慢慢变得模糊起来。故趁这两天空闲，把记忆里最深刻的，时常回想的片段，用文字记录下来，当作这个清明节对父亲的思念吧。父亲，我们想念父亲。</p>
<p><img src="https://yanghaowang.github.io/posts/my-different-qingming/grandpa.jpg" class="img-fluid"></p>
<section id="记忆中的清明" class="level2">
<h2 class="anchored" data-anchor-id="记忆中的清明">记忆中的清明</h2>
<p>往年清明节当天，都是父亲领着我们兄妹几个，上午去上坟，逐个祭拜爷爷奶奶，母亲，及更早的祖辈，挂些纸钱，烧些纸金银包、冥币。晚上在祖屋厅堂供上米饭鱼肉，点香祭拜列祖列宗，每次重复默念的祭词总少不了“父亲不要睡着了，要保佑父亲一身之下的人，保佑大家在外上车下车平平安安、工作顺顺利利，小孩读书年年升级、步步升高，好人相逢，恶人躲避……”。</p>
<p>从1982年到南昌读书，再到84年毕业分配至上饶工作起，因路途遥远、交通不便，记忆中就没有回官坑过清明了。但唇齿间总回味着清明果、蕨菜、小竹笋、猪头花[①]等家乡食物的味道，脑海里放映着石板路旁、小河边、房前屋后、稻田里、漫山遍野的各种油菜花、野花盛开的景象。到1998年，我考取了机动车驾驶证，从此就能自己开车往返工作地和官坑了。再后来，交通路况也逐步好起来了，也买了私家车。虽然因工作变动，我搬到了南昌，但感觉回官坑的路程也不那么遥远了。往后，官坑就成了清明节必须去的地方，这个习惯也就慢慢变成了责任。</p>
</section>
<section id="模范农民" class="level2">
<h2 class="anchored" data-anchor-id="模范农民">模范农民</h2>
<p>小学期间的事，因为年纪小，我大多已经记不得了。只是模糊记着，读小学的时候，我不爱读书，家里给每个人都分配了任务。我的主要任务是早晚放牛，牵牛喝水，投放牛料，打猪草。没有事的时候，我会经常跑到六队队屋里玩。那时父亲是生产队会计，每到生产队分玉米、分红薯的时候，我们小孩就特别高兴，而父亲就要算账，特别忙。每人或每户应分多少，按什么标准（权重）分，而且那时只能用算盘来加减乘除。因此，父亲也成了乡间算盘高手。有一次，县茶厂来招统计员，办事的专员发现父亲是乡间秀才，希望调父亲去县茶厂，可后来大队不同意，就此作罢。那时父亲也常常跟我们讲，经手财会类的事，一分钱都不能少、不能错。后来父亲也不止一次跟我们讲起一个事。有次生产队的社员质疑有一笔上级补助款大家没有分到，而且是好多年前的事。父亲就把账本、单据找出来跟大家仔细讲，多少用于计划生育妇女补助，多少替大家抵交农业税等等，讲得大家心服口服。平常父亲也跟我们几个兄妹讲“命里有时终须有，命里无时莫强求”，我们也时刻把父亲的话记在心里。</p>
<p>去年这个时候我们在父亲房间为他守灵时，看到父亲房间里两把用得破旧的算盘和一些记着生产队账务的落满灰尘的账本、发黄的单据依然挂在昏暗的木板墙上。</p>
<p>也许因为父亲读了点书，且特别尊尚传统文化、古人警言，常常在跟没有读过书的社员们讲道理时，挂着口头禅，经常说“过去老几（辈）人，如何如何,我们应该怎样怎样”。因此，村里人给父亲取了个绰号，叫“清朝”。</p>
<p>当年父亲不仅队长、会计做得称职，田地里的农活、挑驮力气活样样不落下。父亲常常跟我们讲，那时到秋口挑米，到屯溪挑茶是家常便饭。还说有一次清明前后挑担路过段莘溪边一户亲戚家，一口气吃了十八个清明果，可见长途挑担体力消耗之大。</p>
<p>还有一次，不记得我和兄弟谁，进七里源砍柴回家，路过上村对面父亲做砖瓦的草棚时，肚子饿得难受。父亲赶紧跑到棚边上，摘了一个自己种的嫩南瓜，炒起来让我们当饭吃，我们非常高兴，父亲也经常当笑话说起这事。</p>
</section>
<section id="自力更生建房" class="level2">
<h2 class="anchored" data-anchor-id="自力更生建房">自力更生建房</h2>
<p>记得1976年，我11岁，家里人多，祖上分下来的老屋住不下了。经过大队批准，父亲开始在太平灶北边的一个山坳里伐木，从段莘水库移民老屋基捡挑旧砖，在老屋后边大约80平米的菜园地里做了两直传统木屋。父亲常在我们面前自豪地说，当时猪肉价0.74元一斤，做这栋房屋请工匠等总共花费现金大约两千元，其余基本都是自己完成。我和华锋哥虽然也常常帮忙去山上驮一些小方料，放学后也到官坑口挑几块砖，但那时我们力气很小，只能帮一点点忙。想来父亲到老年，右肩驼得厉害，比左肩凸出好多，可能是中年时用力过度所致。何况当时驮木头，从山坳里上来要经过500米左右的羊肠上坡路。官坑也没通公路，从官坑口挑砖也要经过一段600米左右的上岭。一座房子的物料需要多少次日日夜夜的挑运啊！</p>
<p>终于在1978年，一家人住进了新屋，小弟华斌就是在新屋里出生的。也就是这段日子，父亲自力更生、勤劳节俭、精打细算的特质影响了我们兄妹几个一辈子。</p>
</section>
<section id="送我读书" class="level2">
<h2 class="anchored" data-anchor-id="送我读书">送我读书</h2>
<p>1979年，我在官坑附中读完两年制初中，毕业后前往河坑源段莘乡中学读高中。第一次要离开父母，离开官坑，住校读书。可能是年龄小不懂事，不习惯陌生环境，读书兴趣也不高。记得读了一个多月，便借故跑回家里不想读，拿起镰刀就要上山砍柴去，硬是被父亲打回学校的。印象中那是被打得最厉害的一次，我也感觉当时是我犟得最厉害的一次，还回嘴对骂，言语也很难听。如果要说一辈子我有什么对不住父母的话，那是唯一的一次，也是最后悔的一次。</p>
<p>两年高中，我很快就混到了毕业，1981年第一次参加高考。也许是段莘中学英语教学差，大家基本上都报考中专，结果只有一个女生去了上饶卫校。记得恢复高考前几年，段莘中学考上的人很少。官坑村只有两个人，一个是同一个生产队的汪新华，读了上饶师范，另一个是堂叔汪天祥，读了上饶卫校。后来不知是因为官坑有个慈祥的长辈洪应天老师在江湾中学当校长之故，还是华锋哥学了一年手艺又回到学校想读书的事影响了我，或是受父亲经常在我们面前讲“万般皆下品，唯有读书高”的影响，1981年下半年我又到江湾中学复读去了。</p>
<p>记得当时16岁的我，也许是农村人那时普遍营养不良，体重大约70斤左右，很是瘦小。第一天去江湾中学报到是父亲挑着被子和木箱子送我走路去的。快到江湾中学附近，路过一片雪梨地时，记得父亲买了两个让我们尝了尝。</p>
<p>从那天开始，我感觉才真正懂事了，才开始刻苦读书了。一方面，想想父母送两兄弟复读，在农村的确不易，也不多见。另一方面，或许是暑假期间跟着母亲田地里除草，热得受不了。或许是上山摘箬皮卖钱时，头怕山蜂，脚怕毒蛇的情景刺激着我。功夫没有白费，一年后终于以江湾中学第一名的成绩被录取到江西银行学校农村金融专业，更高兴的是华锋哥也同时考进了上饶农校。</p>
</section>
<section id="家书抵万金" class="level2">
<h2 class="anchored" data-anchor-id="家书抵万金">家书抵万金</h2>
<p>在通讯落后、交通不便的日子里，“家书抵万金”是现在很多年轻人无法体会的。就是一元钱的路费常常也舍不得花，乡愁就只能浓缩在一枚八分钱的邮票里了。从到了南昌读书后，直到上世纪九十年代末，与家里的联系就靠这枚小小的邮票了。</p>
<p>我和华锋哥进了中专学校读书后，乡村里许多一辈子跟泥土打交道的亲戚朋友都很羡慕。可是命运却开了个不小的玩笑，好像上帝故意要考验父亲一样，坏消息一个接一个：1982年下半年母亲生病，后来被诊断出是鼻咽癌；1983年大弟华树又生了一次大病，送外地就医；再后来父亲在田里干活时手又被蛇咬了……这些都靠书信来往得知。那时很希望一下课就能收到家里的来信，但信捏在自己手里的时候，又不敢拆开，怕看到坏消息。最后，最不幸的事还是发生了，1983年5月母亲还是离世了。</p>
<p>再后来，父亲家事、农活一个人更忙了，还有弟妹要读书要照顾抚养，有时一两个月都没有时间回我们的信。时间长了，心里就格外担心害怕。直到我和华锋哥毕业参加工作，一切才慢慢好起来。这时我们不仅常常写信向父亲报告一些好消息，也会通过邮局寄点钱回家补贴家用。</p>
<p>1988年，我写信回家，告诉父亲我找对象了，1989年春节带回官坑过年。父亲虽然言语不多，但内心的高兴还是看得出来的。当年4月28日，父亲和华锋哥来上饶参加我的结婚典礼，记得那天晚上，父亲们很晚到上饶。一方面是客车在路上耽误了，另一方面是两个人都没有来过上饶，下车后不认识路。那时小城市即买不到地图，路牌也很不规范，更没有电话手机。记得到我单位上饶农业银行都晚上十点钟了。第二天，新娘下婚车放鞭炮时，父亲也许是激动紧张，用一根火柴，划了好几次都未成功。这时我的一位退休留用的阿姨同事，一把抓过父亲手中的火柴，几根火柴一起划，着了，鞭炮响了。后来，我那位阿姨同事常常在我面前提起这个小插曲。</p>
<p>1990年2月小岛出生，我也是第一时间写信向父亲报喜。转眼到了1994年，华树毕业，分配到婺源邮电局[②]工作，一切都好起来了，交通也改善了，写信的次数就越来越少了。又过了几年，到了本世纪初，官坑外边溪关娣家安装了一部无线电话[③]，我们有急事、好事就通过关娣家电话联系了。好像又过了一年多，华树就帮我们自己家也装了一部无线电话，从那以后就再也没有写过信了，一家人相聚也容易多了。</p>
</section>
<section id="幸福的晚年" class="level2">
<h2 class="anchored" data-anchor-id="幸福的晚年">幸福的晚年</h2>
<p>2005到2006年间，我们四兄妹在双河汇合处合资建新房。那时父亲虽已年近七十，但头脑清晰，很会算账，又有建房经验，仍担任家里的总指挥。记忆中，这是父亲最后做的一件大事。2007年春节，我们兄妹五家大大小小都住到了新房里过年。从那时算起，父亲才开始真正享受自己的晚年生活，吃喝、洗衣有旺生和兴珠伺候。</p>
<p>日子好了，天天都好像过年过节一样，想吃什么都有。电话方便了，不仅座机有了，华树还帮父亲办了手机。有什么事或想谁了，一个电话就解决问题了。交通也方便多了，水泥路、高速路陆续通了。我们兄弟几个也都买了私家车，逢年过节大家总会不约而同地跑去官坑看望父亲。与此同时，我们也了却了心中的乡愁，品尝了小时候的味道。碰上不错的时机，我们也会带父亲出门走走，看看外面的世界，体验一下电视新闻里才看得到的地方。</p>
<p>记得带父亲到南昌过年的时候，父亲说城市里怎么到处是人山人海；记得开车带父亲去赣州玩，父亲还说车子没有坐够；记得路过吉安吃饭时，上了一份驴肉，回来后常常说好吃；带父亲去杭州玩时，父亲总回想小时候书上讲“上有天堂，下有苏杭”，一看西湖怎么这么大；带父亲去上海时，父亲感觉酒店里的自助早餐真实在，东方明珠塔怎么能建得那么高，同时也去看了我爷爷在上海生活期间置办的小屋，了结了多年的心愿。再从上海坐飞机回南昌时，父亲说怎么就只坐了一下下子。</p>
<p>我还记得带父亲去惠州华斌家过年的时候，父亲在街上看到人家过年打赤膊很是惊奇。我还记得父亲，常常讲华锋带着去婺源乡下吃米饭蒸狗肉，低头一口气吃了三小碗。也常讲华斌带父亲去北京时，北京的饺子如何如何实惠。还常讲县里华树家声琴做的饺子、包子是如何如何好吃。</p>
<p>也因为父亲走得多、看得多，在官坑，父亲跟亲朋好友谈天时，或是跟兴珠家游客吹牛时，话题自然丰富了很多。近年来，我问父亲想去哪，他说想去的都去过了，不想了，也许这就是知足吧。</p>
<p>晚年期间，每当我们有好友去官坑玩，或是兴珠家游客高兴起哄时，父亲偶尔也在小院里唱唱婺源小调。我们听得最多的是《劝善记》，虽然调子有些凄凉，但歌中劝大家和谐相处、与人为善的词句让人深受启发，我们兄妹几个也都受益匪浅。</p>
<p>因父亲略知中国民间风水历学，特别是熟悉婺源本地民间风俗礼仪，所以闲空之时官坑本地亲朋好友举办红白喜事、建屋盖房都喜欢请父亲挑日子、看风水、写对联、做司仪。亦或是分家，也愿意请父亲当公证人或代理书写契约。对于这些事，父亲从不开价收费。相反，他总是乐于相助，在忙碌中实现个人价值。</p>
</section>
<section id="最后的时光" class="level2">
<h2 class="anchored" data-anchor-id="最后的时光">最后的时光</h2>
<p>近几年来，父亲的听力减退了，我们也不常通电话。每逢节假日，我几乎都要开车去官坑看父亲。每次只要是讲了大概什么时间会到，父亲一定会站在停车场等候。同样，每次开车离开，父亲也一定会去停车场送别。虽然煽情的话不多，但彼此的内心一定是温暖的，现在这种感觉突然就没有了。</p>
<p>近几年，每次大年三十晚上团圆饭后，父亲都会提着小蓝子给我们大家发红包。无论男女老少，每人200元，很是热闹。小岛在美求学，因此也缺席了多年。但每次父亲见到我，总会提起，“小岛什么时候毕业，让他回来工作”。这份惦记，也许就是父亲心底里对孙辈的挂念吧。</p>
<p>近几年清明节，或是大年初二，父亲带我们去爷爷奶奶坟前祭拜结束后，他都会指着爷爷坟墓右边30米左右的一处空地，跟我们小声说上一句，“那个地方可以，离这也近，我以后可以放那”。去年清明，我问父亲寒食节是怎么来的，为什么婺源规矩不能挂纸钱，父亲跟我讲过后又拿出一本古书让我查对。最后还补上一句，“这本书人家出一万元想收购我都不肯”，又说，“以后这本书就传给你好了”。感觉是父亲自己知道时日不多，在妥善安排后事一样。没想到几天后，他就真要离开我们了。那时也没有机会说上一句话，也许这就是天意。</p>
<p>俗话说，“父母在，家就在。父母离去，人生只剩下归途”。现在终于体会到了其中的深意。在父亲离开的这一年里，我时常想起他过往的点点滴滴。各种场景涌上心头，感觉挥之不去。于是，我打算找个时间做个记录，传于后人。恰好这个清明假期，哪里也去不了，便打开电脑写下这些文字，当作对父亲的周年纪念吧。愿父亲在另一个世界里还是那么乐观、知足、快乐！</p>
<p>华亮</p>
<p>二零二二年农历三月初五 清明节</p>
<hr>
<p>①: 猪头花是官坑一种可以蒸起来吃的野花。</p>
<p>②: 1994年，邮电局负责邮政、电信、移动三项业务。</p>
<p>③: 官坑的无线电话依靠段莘乡山顶一个无线差转台传送信号。</p>


</section>
</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>札记</category>
  <guid>https://yanghaowang.github.io/posts/my-different-qingming/</guid>
  <pubDate>Tue, 05 Apr 2022 07:06:32 GMT</pubDate>
</item>
<item>
  <title>Directed Acyclic Graphs (DAGs)</title>
  <link>https://yanghaowang.github.io/posts/dags/</link>
  <description><![CDATA[ 






<section id="causal-graphs" class="level3">
<h3 class="anchored" data-anchor-id="causal-graphs">Causal Graphs</h3>
<ul>
<li><p>Directed Graph (A affects Y)</p>
<ul>
<li><p>A and Y are known as nodes or vertices (variables)</p></li>
<li><p>The link (edge) between A and Y is an arrow, which means there is a direction (directed path)</p></li>
<li><p>Variables connected by an edge are adjacent</p></li>
</ul>
<p><img src="https://yanghaowang.github.io/posts/dags/DAG_01.png" class="img-fluid"></p></li>
<li><p>Undirected Graph (Association between A and Y)</p>
<p><img src="https://yanghaowang.github.io/posts/dags/DAG_02.png" class="img-fluid"></p></li>
<li><p>Directed Acyclic Graph (DAG)</p>
<ul>
<li>No undirected paths</li>
<li>No cycles</li>
</ul>
<p><img src="https://yanghaowang.github.io/posts/dags/DAG_03.png" class="img-fluid"></p></li>
<li><p>Terminology</p>
<ul>
<li><p>A is Z’s <strong>parent</strong></p></li>
<li><p>B is a <strong>child</strong> of Z</p></li>
<li><p>D is a <strong>decendant</strong> of A</p></li>
<li><p>Z is an <strong>ancestor</strong> of D</p></li>
<li><p>D has two <strong>parents</strong>, B and Z</p></li>
</ul>
<p><img src="https://yanghaowang.github.io/posts/dags/DAG_04.png" class="img-fluid"></p>
<p>We use DAGs to help us determine the set of variables that we need to control in order to achieve ignorability.</p></li>
</ul>
</section>
<section id="relationship-with-probability-distributions" class="level3">
<h3 class="anchored" data-anchor-id="relationship-with-probability-distributions">Relationship with Probability Distributions</h3>
<p>DAGs encode assumptions about dependencies between nodes.</p>
<section id="example-1" class="level5">
<h5 class="anchored" data-anchor-id="example-1">Example 1</h5>
<p><img src="https://yanghaowang.github.io/posts/dags/DAG_05.png" class="img-fluid"></p>
<ul>
<li><p><img src="https://latex.codecogs.com/png.latex?%5CPr(C%5Cmid%20A,B,D)=%5CPr(C)"> i.e., C is independent of all variables</p></li>
<li><p><img src="https://latex.codecogs.com/png.latex?%5CPr(B%5Cmid%20A,C,D)=%5CPr(B%5Cmid%20A)"> i.e.,$ BD$, <img src="https://latex.codecogs.com/png.latex?C%20%5Cmid%20A"></p></li>
<li><p><img src="https://latex.codecogs.com/png.latex?%5CPr(B%5Cmid%20D)%5Cneq%5CPr(B)">, because B and D are marginally dependent</p></li>
<li><p><img src="https://latex.codecogs.com/png.latex?%5CPr(D%5Cmid%20A,%20B,%20C)=%5CPr(D%5Cmid%20A)"></p></li>
</ul>
</section>
<section id="example-2" class="level5">
<h5 class="anchored" data-anchor-id="example-2">Example 2</h5>
<p><img src="https://yanghaowang.github.io/posts/dags/DAG_06.png" class="img-fluid"></p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?%5CPr(A%5Cmid%20B,C,%20D)=%5CPr(A%5Cmid%20D)"> i.e., <img src="https://latex.codecogs.com/png.latex?A%5Cperp%20B,C%5Cmid%20D"></li>
<li><img src="https://latex.codecogs.com/png.latex?%5CPr(D%5Cmid%20A,%20B,C)=%5CPr(D%5Cmid%20A,B)"> i.e., <img src="https://latex.codecogs.com/png.latex?D%5Cperp%20C%5Cmid%20B"></li>
</ul>
</section>
<section id="example-3" class="level5">
<h5 class="anchored" data-anchor-id="example-3">Example 3</h5>
<p><img src="https://yanghaowang.github.io/posts/dags/DAG_07.png" class="img-fluid"></p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?%5CPr(A%5Cmid%20B,C,%20D)=%5CPr(A%5Cmid%20C,D)"> i.e., <img src="https://latex.codecogs.com/png.latex?A%20%5Cperp%20B%20%5Cmid%20C,%20D"></li>
<li><img src="https://latex.codecogs.com/png.latex?%5CPr(D%5Cmid%20A,%20B,C)=%5CPr(D%5Cmid%20A,B)"> i.e., <img src="https://latex.codecogs.com/png.latex?D%5Cperp%20C%5Cmid%20A,%20B"></li>
</ul>
</section>
<section id="decomposition-of-joint-distribution" class="level4">
<h4 class="anchored" data-anchor-id="decomposition-of-joint-distribution">Decomposition of Joint Distribution</h4>
<p>We can decompose the join distribution by sequential conditioning only on sets of parents.</p>
<ul>
<li><p>Start with roots (nodes with no parents)</p></li>
<li><p>Proceed down the descendant line, always conditional on parents</p></li>
</ul>
<section id="example-1-1" class="level5">
<h5 class="anchored" data-anchor-id="example-1-1">Example 1</h5>
<p><img src="https://yanghaowang.github.io/posts/dags/DAG_08.png" class="img-fluid"></p>
<ul>
<li>One root, D; two children of D, A and B</li>
<li><img src="https://latex.codecogs.com/png.latex?%5CPr(A,B,C,D)=%5CPr(D)%5CPr(A%5Cmid%20D)%5CPr(B%5Cmid%20D)%5CPr(C%5Cmid%20B)"></li>
</ul>
</section>
<section id="example-2-1" class="level5">
<h5 class="anchored" data-anchor-id="example-2-1">Example 2</h5>
<p><img src="https://yanghaowang.github.io/posts/dags/DAG_09.png" class="img-fluid"></p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?%5CPr(A,B,C,D)=%5CPr(D)%5CPr(A%5Cmid%20D)%5CPr(B%5Cmid%20D)%5CPr(C%5Cmid%20A,%20B)"></li>
</ul>
</section>
</section>
</section>
<section id="paths-and-associations" class="level3">
<h3 class="anchored" data-anchor-id="paths-and-associations">Paths and Associations</h3>
<section id="type-of-paths" class="level4">
<h4 class="anchored" data-anchor-id="type-of-paths">Type of Paths</h4>
<ul>
<li><p>Fork</p>
<p><img src="https://yanghaowang.github.io/posts/dags/DAG_10.png" class="img-fluid"></p></li>
<li><p>Chain</p>
<p><img src="https://yanghaowang.github.io/posts/dags/DAG_11.png" class="img-fluid"></p></li>
<li><p>Inverted Fork</p>
<ul>
<li>E is a <strong>collider</strong></li>
</ul>
<p><img src="https://yanghaowang.github.io/posts/dags/DAG_12.png" class="img-fluid"></p></li>
</ul>
</section>
</section>
<section id="conditional-independence-d-separation" class="level3">
<h3 class="anchored" data-anchor-id="conditional-independence-d-separation">Conditional Independence (d-separation)</h3>
<p>d-separation: “d” stands for dependence.</p>
<section id="blocking" class="level4">
<h4 class="anchored" data-anchor-id="blocking">Blocking</h4>
<ul>
<li><p>Paths and associations can be <em>blocked</em> by conditioning on nodes in the path.</p></li>
<li><p>However, the opposite situation occurs in inverted paths if a collider is conditioned on.</p></li>
</ul>
</section>
<section id="rules-of-d-separation" class="level4">
<h4 class="anchored" data-anchor-id="rules-of-d-separation">Rules of d-separation</h4>
<p>A path is d-separated by a set of nodes C if:</p>
<ul>
<li><p>It contains a chain (e.g., <img src="https://latex.codecogs.com/png.latex?D%5Crightarrow%20E%5Crightarrow%20F">) and the middle part is in C (i.e., <img src="https://latex.codecogs.com/png.latex?E">)</p>
<blockquote class="blockquote">
<p>Example D is temperature, E is sidewalks are icy, and F is someone falls. If we restrict to situation where sidewalks are icy (condition on G), then temperature and falling are not associated via this path.</p>
</blockquote></li>
<li><p>It contains a fork (e.g., <img src="https://latex.codecogs.com/png.latex?D%5Cleftarrow%20E%20%5Crightarrow%20F">) and the middle part is in C (i.e., <img src="https://latex.codecogs.com/png.latex?E">)</p>
<blockquote class="blockquote">
<p>In this path, D and F are dependent because of E. If E is given or fixed, E no longer affects D and F. Hence, they are independent (i.e., the path is blocked).</p>
</blockquote></li>
<li><p>It contains an inverted fork (e.g., <img src="https://latex.codecogs.com/png.latex?D%5Crightarrow%20E%5Cleftarrow%20F">) and the middle part is NOT in C, nor are any descendants of it. In other words, no need to control anything in this path where <img src="https://latex.codecogs.com/png.latex?E"> is collider and the relation between <img src="https://latex.codecogs.com/png.latex?D"> and <img src="https://latex.codecogs.com/png.latex?F"> is independent.</p>
<blockquote class="blockquote">
<p>Example <img src="https://latex.codecogs.com/png.latex?D"> is the state of an ON/OFF switch, while <img src="https://latex.codecogs.com/png.latex?F"> is the state of another switch. Both switches control the same light. We decide the state of <img src="https://latex.codecogs.com/png.latex?D"> and <img src="https://latex.codecogs.com/png.latex?F"> by flipping a fair coin, respectively. <img src="https://latex.codecogs.com/png.latex?E"> is the event that the light is ON, where the light is ON if only if both switches are ON.</p>
<p>Hence, <img src="https://latex.codecogs.com/png.latex?D"> and <img src="https://latex.codecogs.com/png.latex?F"> are independent if the information on <img src="https://latex.codecogs.com/png.latex?E"> is not known. In contrast, <img src="https://latex.codecogs.com/png.latex?D"> and <img src="https://latex.codecogs.com/png.latex?F"> are dependent if <img src="https://latex.codecogs.com/png.latex?E"> is given/controlled.</p>
</blockquote></li>
</ul>
</section>
</section>
<section id="confounding-revisited" class="level3">
<h3 class="anchored" data-anchor-id="confounding-revisited">Confounding Revisited</h3>
<section id="confounders" class="level4">
<h4 class="anchored" data-anchor-id="confounders">Confounders</h4>
<p>A confounder is a variable that affects both the treatment and the outcome.</p>
<section id="example" class="level5">
<h5 class="anchored" data-anchor-id="example">Example</h5>
<p><img src="https://yanghaowang.github.io/posts/dags/DAG_13.png" class="img-fluid"></p>
<ul>
<li><p>V affects A directly and Y indirectly through W</p></li>
<li><p>V is a confounder in the relation between A and Y</p></li>
</ul>
</section>
</section>
<section id="frontdoor-paths" class="level4">
<h4 class="anchored" data-anchor-id="frontdoor-paths">Frontdoor Paths</h4>
<p>A frontdoor path from A to Y is one that begins with an arrow emanating out of A.</p>
</section>
<section id="backdoor-paths" class="level4">
<h4 class="anchored" data-anchor-id="backdoor-paths">Backdoor Paths</h4>
<p>A backdoor path from treatment A to outcome Y is a path from A to Y that travels through arrows going into A.</p>
<blockquote class="blockquote">
<p><strong>Note</strong>: A path is a link between two variables regardless of arrow directions</p>
</blockquote>
<section id="example-4" class="level5">
<h5 class="anchored" data-anchor-id="example-4">Example</h5>
<p><img src="https://yanghaowang.github.io/posts/dags/DAG_14.png" class="img-fluid"></p>
<ul>
<li><p>Frontdoor path: <img src="https://latex.codecogs.com/png.latex?A%5Crightarrow%20Z%5Crightarrow%20Y"></p>
<p>Our interest is in the causal relationship between A and Y, where a part of this relationship is through the effect that A has on Z. It is not something we are concerned about at this point. We are interested in just how A affects Y regardless of what path it&nbsp;takes to get there.</p></li>
<li><p>Backdoor path: <img src="https://latex.codecogs.com/png.latex?A%5Cleftarrow%20X%20%5Crightarrow%20Y"></p>
<p>This backdoor path does not involve any arrows coming out of A. So there’s no treatment effect involved there. But A and Y are still associated with each other through that path.&nbsp;So this is something we have to worry about. Because if we look at just marginal associations between A and Y,&nbsp;some of that association will be due to a causal effect of A and Y, while some of it also could be because X causes both A and Y. <em>Backdoor paths confound the relationship between A and Y and need to be blocked.</em></p></li>
</ul>
</section>
</section>
</section>
<section id="backdoor-path-criterion" class="level3">
<h3 class="anchored" data-anchor-id="backdoor-path-criterion">Backdoor Path Criterion</h3>
<p>A set of variables X is sufficient to control for confounding if:</p>
<ol type="1">
<li><p>it blocks all backdoor paths from treatment to outcome</p></li>
<li><p>it does not include any descendants of treatment.</p></li>
</ol>
<section id="example-5" class="level5">
<h5 class="anchored" data-anchor-id="example-5">Example</h5>
<p><img src="https://yanghaowang.github.io/posts/dags/DAG_15.png" class="img-fluid"></p>
<ul>
<li><p>There is one backdoor path from A to Y, that is, <img src="https://latex.codecogs.com/png.latex?A%5Cleftarrow%20V%5Crightarrow%20M%5Cleftarrow%20W%5Crightarrow%20Y"></p>
<ul>
<li><p>It is blocked by a collider M</p></li>
<li><p>No confounding (Information from V and W does not flow to Y and A because of M)</p></li>
</ul></li>
<li><p>Set of variables that are sufficient to control for confounding:</p>
<ul>
<li><p>Solutions: {},{V},{W},{M, W}, {M, V}, {M, V, W}</p></li>
<li><p>Never only control {M} since it will open a path between A and Y that is not causal</p></li>
</ul></li>
</ul>
<p><img src="https://yanghaowang.github.io/posts/dags/DAG_16.png" class="img-fluid"></p>
<ul>
<li><p>There are two paths</p>
<ul>
<li><p><img src="https://latex.codecogs.com/png.latex?A%5Cleftarrow%20Z%5Cleftarrow%20V%5Crightarrow%20Y"></p>
<ul>
<li><p>No colliders</p></li>
<li><p>Solutions: {Z}, {V}, or {Z, V}</p></li>
</ul></li>
<li><p><img src="https://latex.codecogs.com/png.latex?A%5Cleftarrow%20W%5Crightarrow%20Z%5Cleftarrow%20V%5Crightarrow%20Y"></p>
<ul>
<li><p>Z is a collider</p></li>
<li><p>Solutions: {V}, or {Z, V}, {Z, W}, and {Z, V, W}</p>
<p>Once we control for Z, we need to block the backdoor path by including V, or W, or V and W</p></li>
</ul></li>
</ul></li>
</ul>
</section>
<section id="summary" class="level4">
<h4 class="anchored" data-anchor-id="summary">Summary</h4>
<p>To use the backdoor path criterion, we are required to know the <em>whole DAG</em>.</p>
</section>
</section>
<section id="disjunctive-cause-criterion" class="level3">
<h3 class="anchored" data-anchor-id="disjunctive-cause-criterion">Disjunctive Cause Criterion</h3>
<p>We do not need to know the whole graph, but rather, the list of variables that affect exposure or outcome.</p>
<section id="example-6" class="level5">
<h5 class="anchored" data-anchor-id="example-6">Example</h5>
<ul>
<li><p>Observed pre-treatment variables: {M, W, V}</p></li>
<li><p>Unobserved pre-treatment variables: {U1, U2}</p></li>
<li><p>Suppose W and V are causes of A, Y, or both and M is not a cause of either A or Y</p></li>
</ul>
<p><strong>Solution 1</strong>: Use all pre-treatment covariates, i.e., {M, W, V}</p>
<p><strong>Solution 2</strong>: Use variables <u>based on disjunctive cause criterion</u>, i.e., {W, V}</p>
<p>Let’s check if these solutions fit in the DAG for <img src="https://latex.codecogs.com/png.latex?A%5Crightarrow%20Y"></p>
<p><strong>Hypothetical DAG 1</strong></p>
<p><img src="https://yanghaowang.github.io/posts/dags/DAG_17.png" class="img-fluid"></p>
<p><br></p>
<table class="caption-top table">
<thead>
<tr class="header">
<th></th>
<th style="text-align: center;">Satisfies Backdoor Path Criterion</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Solution 1&nbsp;{M, W, V}</td>
<td style="text-align: center;">Yes</td>
</tr>
<tr class="even">
<td>Solution 2&nbsp;{W, V}</td>
<td style="text-align: center;">Yes</td>
</tr>
</tbody>
</table>
<p><strong>Hypothetical DAG 2</strong></p>
<p><img src="https://yanghaowang.github.io/posts/dags/DAG_18.png" class="img-fluid"></p>
<p><br></p>
<table class="caption-top table">
<thead>
<tr class="header">
<th></th>
<th style="text-align: center;">Satisfies Backdoor Path Criterion</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Solution 1&nbsp;{M, W, V}</td>
<td style="text-align: center;">Yes</td>
</tr>
<tr class="even">
<td>Solution 2&nbsp;{W, V}</td>
<td style="text-align: center;">Yes</td>
</tr>
</tbody>
</table>
<p><strong>Hypothetical DAG 3</strong></p>
<p><img src="https://yanghaowang.github.io/posts/dags/DAG_19.png" class="img-fluid"></p>
<p><br></p>
<table class="caption-top table">
<thead>
<tr class="header">
<th></th>
<th style="text-align: center;">Satisfies Backdoor Path Criterion</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Solution 1&nbsp;{M, W, V}</td>
<td style="text-align: center;">No (b/c M opens the backdoor path)</td>
</tr>
<tr class="even">
<td>Solution 2&nbsp;{W, V}</td>
<td style="text-align: center;">Yes</td>
</tr>
</tbody>
</table>
<p><strong>Hypothetical DAG 4</strong></p>
<p><img src="https://yanghaowang.github.io/posts/dags/DAG_20.png" class="img-fluid"></p>
<p><br></p>
<table class="caption-top table">
<thead>
<tr class="header">
<th></th>
<th style="text-align: center;">Satisfies Backdoor Path Criterion</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Solution 1&nbsp;{M, W, V}</td>
<td style="text-align: center;">No (b/c W opens the backdoor path)</td>
</tr>
<tr class="even">
<td>Solution 2&nbsp;{W, V}</td>
<td style="text-align: center;">No (b/c W opens the backdoor path)</td>
</tr>
</tbody>
</table>
</section>
<section id="summary-1" class="level4">
<h4 class="anchored" data-anchor-id="summary-1">Summary</h4>
<p>The disjunctive cause criterion:</p>
<ul>
<li><p>does not always select the smallest set of variables to control for (e.g., if we only have one collider in the whole DAG, the smallest set is <img src="https://latex.codecogs.com/png.latex?%5Cempty">, that is, doing nothing)</p></li>
<li><p>but is conceptually simpler (i.e., list variables that are causes of treatment or outcome or both)</p></li>
<li><p>is guaranteed to select a set of variables that are sufficient to control for confounding if</p>
<ul>
<li><p>such a set exists</p></li>
<li><p>all of the observed causes of A and Y are correctly identified (no need to know the whole DAG but do have to know about the relationship between observed variables)</p></li>
</ul></li>
</ul>


</section>
</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Causal</category>
  <category>Causal-DAG</category>
  <guid>https://yanghaowang.github.io/posts/dags/</guid>
  <pubDate>Thu, 10 Mar 2022 20:07:33 GMT</pubDate>
</item>
<item>
  <title>Review on Causal Inference (Part 3)</title>
  <link>https://yanghaowang.github.io/posts/causal-inference-econ-3/</link>
  <description><![CDATA[ 






<section id="practice-6-regression-discontinuity---sharp" class="level2">
<h2 class="anchored" data-anchor-id="practice-6-regression-discontinuity---sharp">Practice 6: Regression Discontinuity - Sharp</h2>
<p>Data in this example include student test scores from an entrance and an exit exam. Students who score 70 or below in the entrance exam are automatically enrolled in a free tutoring program and receive assistance throughout the year. At the end of the school year, students take an exit exam (with a maximum of 100 points) to measure how much they learned overall.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1">tutoring <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fread</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"RD/tutoring_program.csv"</span>)</span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">print</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Number of Rows:'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Number of Columns:'</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dim</span>(tutoring)))</span></code></pre></div></div>
<pre><code>## [1] "Number of Rows: 1000" "Number of Columns: 4"</code></pre>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(tutoring)</span></code></pre></div></div>
<pre><code>##    id entrance_exam exit_exam tutoring
## 1:  1          92.4      78.1    FALSE
## 2:  2          72.8      58.2    FALSE
## 3:  3          53.7      62.0     TRUE
## 4:  4          98.3      67.5    FALSE
## 5:  5          69.7      54.1     TRUE
## 6:  6          68.1      60.1     TRUE</code></pre>
<p>There are 5 steps in a causal study using regression discontinuity (RD) technique:</p>
<p><strong>Step 1</strong>: Determine if process of assigning treatment is rule based</p>
<p><strong>Step 2</strong>: Determine if the design is fuzzy or sharp</p>
<p><strong>Step 3</strong>: Check for discontinuity in running variable around cutpoint</p>
<p><strong>Step 4</strong>: Check for discontinuity in outcome across running variable</p>
<p><strong>Step 5</strong>: Measure the size of the effect</p>
<section id="sharp-or-fuzzy" class="level3">
<h3 class="anchored" data-anchor-id="sharp-or-fuzzy">Sharp or Fuzzy</h3>
<p>Check in plot and verify in table <img src="https://yanghaowang.github.io/posts/causal-inference-econ-3/unnamed-chunk-2-1.png" class="img-fluid"></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1">tutoring[, .(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">group_min =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(entrance_exam), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">group_max =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(entrance_exam))</span>
<span id="cb5-2">         , by <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'tutoring'</span>]</span></code></pre></div></div>
<pre><code>##    tutoring group_min group_max
## 1:    FALSE      70.1      99.8
## 2:     TRUE      28.8      70.0</code></pre>
<p>We confirm that there is a sharp cutoff at 70.</p>
</section>
<section id="manipulation-testing" class="level3">
<h3 class="anchored" data-anchor-id="manipulation-testing">Manipulation Testing</h3>
<p>Check if there was any manipulation in the running variable. For example, students wanted to enroll in the program, so they did poorly on the exam to get under 70 in purpose. First, we’ll make a histogram of the running variable (test scores) and see if there are any big jumps around the threshold.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(tutoring, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> entrance_exam, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> tutoring)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb7-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_histogram</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">binwidth =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">color =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"white"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">boundary =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">70</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb7-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_vline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xintercept =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">70</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb7-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Entrance exam score"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Count"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"In program"</span>)</span></code></pre></div></div>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-econ-3/unnamed-chunk-4-1.png" class="img-fluid"></p>
<p>There’s a tiny visible difference between the height of the bars right before and right after the score of 70. We can check to see if that jump is statistically significant with a McCrary density test. This puts data into bins like a histogram, and then plots the averages and confidence intervals of those bins.</p>
<ul>
<li><p>If the confidence intervals of the density lines don’t overlap, then there’s likely something systematically wrong with how the test was scored (i.e.&nbsp;too many people getting 69 vs 71).</p></li>
<li><p>If the confidence intervals overlap, there’s not any significant difference around the threshold and we’re fine.</p></li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1">test_density <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rddensity</span>(tutoring<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>entrance_exam, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">c =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">70</span>)</span>
<span id="cb8-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>(test_density)</span></code></pre></div></div>
<pre><code>## 
## Manipulation testing using local polynomial density estimation.
## 
## Number of obs =       1000
## Model =               unrestricted
## Kernel =              triangular
## BW method =           estimated
## VCE method =          jackknife
## 
## c = 70                Left of c           Right of c          
## Number of obs         237                 763                 
## Eff. Number of obs    208                 577                 
## Order est. (p)        2                   2                   
## Order bias (q)        3                   3                   
## BW est. (h)           22.444              19.966              
## 
## Method                T                   P &gt; |T|             
## Robust                -0.5521             0.5809              
## 
## 
## P-values of binomial tests (H0: p=0.5).
## 
## Window Length / 2          &lt;c     &gt;=c    P&gt;|T|
## 0.300                       9      11    0.8238
## 0.600                      15      16    1.0000
## 0.900                      17      19    0.8679
## 1.200                      22      22    1.0000
## 1.500                      26      29    0.7877
## 1.800                      34      35    1.0000
## 2.100                      41      44    0.8284
## 2.400                      43      51    0.4705
## 2.700                      46      56    0.3729
## 3.000                      51      61    0.3952</code></pre>
<p>Let’s focus on the t-test result, which is presented on the line starting with “Robust.” It shows the t-test for the difference in the two points on either side of the cutpoint in the plot. Notice in the plot that the confidence intervals overlap substantially. The p-value for the size of that overlap is 0.5809. So we don’t have good evidence that there’s a significant difference between the two lines.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1">plot_density_test <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rdplotdensity</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rdd =</span> test_density,</span>
<span id="cb10-2">                                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">X =</span> tutoring<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>entrance_exam,</span>
<span id="cb10-3">                                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">type =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"both"</span>)</span></code></pre></div></div>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-econ-3/unnamed-chunk-6-1.png" class="img-fluid"></p>
<p><strong>Note</strong>: Bias correction is only used for the construction of confidence intervals, but not for point estimation. So we see some points are out of the confidence intervals.</p>
</section>
<section id="discontinuity-in-outcome" class="level3">
<h3 class="anchored" data-anchor-id="discontinuity-in-outcome">Discontinuity in Outcome</h3>
<p>So far, we have known this is a sharp design and that there’s no manipulation on the entrance exam scores around the threshold–70. Now we can finally see if there’s a discontinuity in the exit exam scores based on the participation in the tutoring program.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb11-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(tutoring, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> entrance_exam, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> exit_exam, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">color =</span> tutoring)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb11-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alpha =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb11-3">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Add a line based on a linear model for the people scoring 70 or less</span></span>
<span id="cb11-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_smooth</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">filter</span>(tutoring, entrance_exam <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">70</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"loess"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">formula =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'y ~ x'</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb11-5">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Add a line based on a linear model for the people scoring more than 70</span></span>
<span id="cb11-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_smooth</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">filter</span>(tutoring, entrance_exam <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">70</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"loess"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">formula =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'y ~ x'</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb11-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_vline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xintercept =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">70</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb11-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Entrance exam score"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Exit exam score"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">color =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Used tutoring"</span>)</span></code></pre></div></div>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-econ-3/unnamed-chunk-7-1.png" class="img-fluid"></p>
<p>Based on this graph, there’s a clear discontinuity, suggesting the participation in the tutoring program boosted the exit exam scores.</p>
</section>
<section id="parametric-estimation-regression" class="level3">
<h3 class="anchored" data-anchor-id="parametric-estimation-regression">Parametric Estimation (Regression)</h3>
<ul>
<li>How big is this discontinuity?</li>
<li>Is it statistically significant?</li>
</ul>
<p>We can check the size in a parametric method (i.e.&nbsp;using <code>lm()</code> with specific parameters and coefficients). Particularly, We estimate in a linear regression specified as following,</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Ctext%7BExit%20exam%7D%20=%20%5Cbeta_0%20+%20%5Cbeta_1%5Ctext%7BEntrance%20exam%20score%7D_%7B%5Ctext%7Bcentered%7D%7D%20+%0A%5Cbeta_2%5Ctext%7BTutoring%20program%7D%20+%20%5Cepsilon*.%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Ctext%7BEntrance%20exam%20score%7D_%7B%5Ctext%7Bcentered%7D%7D"> shows how many points away from the threshold <img src="https://latex.codecogs.com/png.latex?70"></p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?%5Cbeta_0">: This is the intercept. Since we centered <em>entrance</em> exam scores, it shows the average <em>exit</em> exam score at the threshold. People who scored 70.001 points on the entrance exam had an average of 59.4 points on the exit exam.</li>
<li><img src="https://latex.codecogs.com/png.latex?%5Cbeta_1">: This represents the slope of the linear equation on both sides of the threshold.</li>
<li><img src="https://latex.codecogs.com/png.latex?%5Cbeta_2">: This is the coefficient of interest, suggesting the causal effect of participation in the tutoring program.</li>
</ul>
<section id="robustness-check" class="level4">
<h4 class="anchored" data-anchor-id="robustness-check">Robustness Check</h4>
<ol type="1">
<li><p>We can include extra demographics and use a polynomial regression including <img src="https://latex.codecogs.com/png.latex?%5Ctext%7Bentrance%7D_%5Ctext%7Bcentered%7D%5E2">, <img src="https://latex.codecogs.com/png.latex?%5Ctext%7Bentrance%7D_%5Ctext%7Bcentered%7D%5E3">, or <img src="https://latex.codecogs.com/png.latex?%5Ctext%7Bentrance%7D_%5Ctext%7Bcentered%7D%5E4"> to fit the data as close as possible.</p></li>
<li><p>We care most about the observations right around the threshold rather than observations far away from the center. Therefore, we should only include the students who had scores just barely under and over 70. Accordingly, We can fit the same model and restrict it to students within a smaller window, or bandwidth, like <img src="https://latex.codecogs.com/png.latex?70%5Cpm10">, or <img src="https://latex.codecogs.com/png.latex?70%5Cpm5">.</p></li>
</ol>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1">tutoring[, entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">=</span> entrance_exam <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">70</span>]</span>
<span id="cb12-2"></span>
<span id="cb12-3">model_simple <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(exit_exam <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> tutoring,</span>
<span id="cb12-4">                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> tutoring)</span>
<span id="cb12-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># round(summary(model_simple)$coef, 4)</span></span>
<span id="cb12-6"></span>
<span id="cb12-7">model_poly <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(exit_exam <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">I</span>((entrance_centered<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> </span>
<span id="cb12-8">                   <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">I</span>((entrance_centered<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">I</span>((entrance_centered<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> </span>
<span id="cb12-9">                   tutoring, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> tutoring)</span>
<span id="cb12-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># round(summary(model_ploy)$coef, 4)</span></span>
<span id="cb12-11"></span>
<span id="cb12-12">model_bw_10 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(exit_exam <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> tutoring,</span>
<span id="cb12-13">                  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">filter</span>(tutoring,</span>
<span id="cb12-14">                                entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span></span>
<span id="cb12-15">                                  entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>))</span>
<span id="cb12-16"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># round(summary(model_bw_10)$coef, 4)</span></span>
<span id="cb12-17"></span>
<span id="cb12-18">model_bw_5 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(exit_exam <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> tutoring,</span>
<span id="cb12-19">                 <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">filter</span>(tutoring,</span>
<span id="cb12-20">                               entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span></span>
<span id="cb12-21">                                 entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>))</span>
<span id="cb12-22"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># round(summary(model_bw_5)$coef, 4)</span></span>
<span id="cb12-23"></span>
<span id="cb12-24">model_bw_5_poly <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(exit_exam <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">I</span>((entrance_centered<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-25">                        <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">I</span>((entrance_centered<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">I</span>((entrance_centered<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> </span>
<span id="cb12-26">                        tutoring,</span>
<span id="cb12-27">                      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">filter</span>(tutoring,</span>
<span id="cb12-28">                                    entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span></span>
<span id="cb12-29">                                      entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>))</span>
<span id="cb12-30"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># round(summary(model_bw_5_poly)$coef, 4)</span></span></code></pre></div></div>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-econ-3/table1.png" class="img-fluid"></p>
<p>The effect of tutoring differs a lot across these different models, from 9.1 to 10.8. The comparison between RMSEs from <code>model_bw_5</code> and <code>model_bw_5_poly</code> might suggest the overfitting issue resulting from the over-specification with several polynomial terms and the small size of sample.</p>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-econ-3/unnamed-chunk-10-1.png" class="img-fluid"></p>
</section>
</section>
<section id="nonparametric-estimation-kernel" class="level3">
<h3 class="anchored" data-anchor-id="nonparametric-estimation-kernel">Nonparametric Estimation (Kernel)</h3>
<p>Instead of using linear regressions, we can use nonparametric methods (i.e.&nbsp;using kernel functions to determine the weights of observations and fit the data in non-linear function forms). The <code>rdrobust()</code> function makes it easy to estimate the causal effect at the cutoff with nonparametric methods.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb13-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rdrobust</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> tutoring<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>exit_exam, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> tutoring<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>entrance_exam, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">c =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">70</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%&gt;%</span></span>
<span id="cb13-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>()</span></code></pre></div></div>
<pre><code>## [1] "Mass points detected in the running variable."
## Call: rdrobust
## 
## Number of Obs.                 1000
## BW type                       mserd
## Kernel                   Triangular
## VCE method                       NN
## 
## Number of Obs.                  237          763
## Eff. Number of Obs.             144          256
## Order est. (p)                    1            1
## Order bias  (q)                   2            2
## BW est. (h)                   9.969        9.969
## BW bias (b)                  14.661       14.661
## rho (h/b)                     0.680        0.680
## Unique Obs.                     155          262
## 
## =============================================================================
##         Method     Coef. Std. Err.         z     P&gt;|z|      [ 95% C.I. ]       
## =============================================================================
##   Conventional    -8.578     1.601    -5.359     0.000   [-11.715 , -5.441]    
##         Robust         -         -    -4.352     0.000   [-12.101 , -4.587]    
## =============================================================================</code></pre>
<ul>
<li>The estimate of the causal effect is present in the table. It shows tutoring program causes an 8-point change in exit exam scores. Confidence intervals are constructed with normal Std. Err (conventional) and robust Std. Err (robust).</li>
<li>The model used a bandwidth of 9.969 (<code>BW est. (h)</code> in the output), which means it includes students with test scores between ~60 and ~80.</li>
<li>The model used a triangular kernel. The kernel decides how much weight to give to observations around the cutoff. The closer to the cutoff, the larger the weight. You can use different kernels and <a href="https://en.wikipedia.org/wiki/Kernel_(statistics)#Kernel_functions_in_common_use">this Wikipage</a> has a nice summary.</li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb15-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rdplot</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> tutoring<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>exit_exam, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> tutoring<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>entrance_exam, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">c =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">70</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nbins =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>,</span>
<span id="cb15-2">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x.label =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Entrance exam score"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y.label =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Exit exam score"</span>)</span></code></pre></div></div>
<pre><code>## [1] "Mass points detected in the running variable."</code></pre>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-econ-3/unnamed-chunk-12-1.png" class="img-fluid"></p>
<p><strong>Note</strong>: Points in the graph are not the actual observations in the dataset. The <code>rdplot()</code> function makes bins of points (like a histogram) and then shows the average outcome within each bin. The argument <code>nbins</code> and <code>binselect</code> can be specified accordingly. Additionally, the plot part in the <code>rdplot()</code> output is a <code>ggplot()</code> object and hence inherit the associated features/functionalities.</p>
<section id="robustness-check-1" class="level4">
<h4 class="anchored" data-anchor-id="robustness-check-1">Robustness Check</h4>
<ol type="1">
<li><p>Try different Kernel functions</p>
<blockquote class="blockquote">
<p>By default <code>rdrobust()</code> uses a triangular kernel (linearly decreasing weights). We can also use Epanechnikov (non-linearly decreasing weights) or uniform (equal weights, i.e., unweighted).</p>
</blockquote></li>
<li><p>Try different the bandwidth algorithms</p></li>
</ol>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb17-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rdbwselect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> tutoring<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>exit_exam, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> tutoring<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>entrance_exam, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">c =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">70</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">all =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%&gt;%</span></span>
<span id="cb17-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>()</span></code></pre></div></div>
<pre><code>## [1] "Mass points detected in the running variable."
## Call: rdbwselect
## 
## Number of Obs.                 1000
## BW type                         All
## Kernel                   Triangular
## VCE method                       NN
## 
## Number of Obs.                  237          763
## Order est. (p)                    1            1
## Order bias  (q)                   2            2
## Unique Obs.                     155          262
## 
## =======================================================
##                   BW est. (h)    BW bias (b)
##             Left of c Right of c  Left of c Right of c
## =======================================================
##      mserd     9.969      9.969     14.661     14.661
##     msetwo    11.521     10.054     17.067     14.907
##     msesum    12.044     12.044     17.631     17.631
##   msecomb1     9.969      9.969     14.661     14.661
##   msecomb2    11.521     10.054     17.067     14.907
##      cerrd     7.058      7.058     14.661     14.661
##     certwo     8.156      7.118     17.067     14.907
##     cersum     8.526      8.526     17.631     17.631
##   cercomb1     7.058      7.058     14.661     14.661
##   cercomb2     8.156      7.118     17.067     14.907
## =======================================================</code></pre>
<ol type="1">
<li>Compare the results using the ideal bandwidth, twice the ideal, and half the ideal</li>
</ol>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb19-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Ideal bandwidth </span></span>
<span id="cb19-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rdbwselect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> tutoring<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>exit_exam, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> tutoring<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>entrance_exam, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">c =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">70</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%&gt;%</span></span>
<span id="cb19-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>()</span></code></pre></div></div>
<pre><code>## [1] "Mass points detected in the running variable."
## Call: rdbwselect
## 
## Number of Obs.                 1000
## BW type                       mserd
## Kernel                   Triangular
## VCE method                       NN
## 
## Number of Obs.                  237          763
## Order est. (p)                    1            1
## Order bias  (q)                   2            2
## Unique Obs.                     155          262
## 
## =======================================================
##                   BW est. (h)    BW bias (b)
##             Left of c Right of c  Left of c Right of c
## =======================================================
##      mserd     9.969      9.969     14.661     14.661
## =======================================================</code></pre>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb21-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rdrobust</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> tutoring<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>exit_exam, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> tutoring<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>entrance_exam, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">c =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">70</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">h =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">9.969</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%&gt;%</span></span>
<span id="cb21-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>()</span></code></pre></div></div>
<pre><code>## [1] "Mass points detected in the running variable."
## Call: rdrobust
## 
## Number of Obs.                 1000
## BW type                      Manual
## Kernel                   Triangular
## VCE method                       NN
## 
## Number of Obs.                  237          763
## Eff. Number of Obs.             144          256
## Order est. (p)                    1            1
## Order bias  (q)                   2            2
## BW est. (h)                   9.969        9.969
## BW bias (b)                   9.969        9.969
## rho (h/b)                     1.000        1.000
## Unique Obs.                     155          262
## 
## =============================================================================
##         Method     Coef. Std. Err.         z     P&gt;|z|      [ 95% C.I. ]       
## =============================================================================
##   Conventional    -8.578     1.601    -5.359     0.000   [-11.715 , -5.441]    
##         Robust         -         -    -3.276     0.001   [-12.483 , -3.138]    
## =============================================================================</code></pre>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb23" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb23-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rdrobust</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> tutoring<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>exit_exam, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> tutoring<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>entrance_exam, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">c =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">70</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">h =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">9.969</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%&gt;%</span></span>
<span id="cb23-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>()</span></code></pre></div></div>
<pre><code>## [1] "Mass points detected in the running variable."
## Call: rdrobust
## 
## Number of Obs.                 1000
## BW type                      Manual
## Kernel                   Triangular
## VCE method                       NN
## 
## Number of Obs.                  237          763
## Eff. Number of Obs.             206          577
## Order est. (p)                    1            1
## Order bias  (q)                   2            2
## BW est. (h)                  19.938       19.938
## BW bias (b)                  19.938       19.938
## rho (h/b)                     1.000        1.000
## Unique Obs.                     155          262
## 
## =============================================================================
##         Method     Coef. Std. Err.         z     P&gt;|z|      [ 95% C.I. ]       
## =============================================================================
##   Conventional    -9.151     1.130    -8.100     0.000   [-11.365 , -6.937]    
##         Robust         -         -    -4.980     0.000   [-11.670 , -5.078]    
## =============================================================================</code></pre>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb25" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb25-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rdrobust</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> tutoring<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>exit_exam, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> tutoring<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>entrance_exam, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">c =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">70</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">h =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">9.969</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%&gt;%</span></span>
<span id="cb25-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>()</span></code></pre></div></div>
<pre><code>## [1] "Mass points detected in the running variable."
## Call: rdrobust
## 
## Number of Obs.                 1000
## BW type                      Manual
## Kernel                   Triangular
## VCE method                       NN
## 
## Number of Obs.                  237          763
## Eff. Number of Obs.              82          109
## Order est. (p)                    1            1
## Order bias  (q)                   2            2
## BW est. (h)                   4.984        4.984
## BW bias (b)                   4.984        4.984
## rho (h/b)                     1.000        1.000
## Unique Obs.                     155          262
## 
## =============================================================================
##         Method     Coef. Std. Err.         z     P&gt;|z|      [ 95% C.I. ]       
## =============================================================================
##   Conventional    -8.201     2.348    -3.493     0.000   [-12.803 , -3.600]    
##         Robust         -         -    -2.032     0.042   [-13.618 , -0.246]    
## =============================================================================</code></pre>
</section>
</section>
</section>
<section id="practice-7-regression-discontinuity---fuzzy" class="level2">
<h2 class="anchored" data-anchor-id="practice-7-regression-discontinuity---fuzzy">Practice 7: Regression Discontinuity - Fuzzy</h2>
<p>In the sharp RD example in Practice 6, it was fairly easy to measure the size of the jump at the cutoff because compliance was perfect. No people who scored above the threshold used the tutoring program, and nobody who qualified for the program did not participate.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb27" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb27-1">tutoring_fuzzy <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fread</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"RD/tutoring_program_fuzzy.csv"</span>)</span>
<span id="cb27-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">print</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Number of Rows:'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Number of Columns:'</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dim</span>(tutoring_fuzzy)))</span></code></pre></div></div>
<pre><code>## [1] "Number of Rows: 1000" "Number of Columns: 5"</code></pre>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb29" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb29-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># kbl(head(tutoring_fuzzy)) %&gt;%</span></span>
<span id="cb29-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#   kable_paper() %&gt;%</span></span>
<span id="cb29-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#   scroll_box(width = "100%") # height = "400px"</span></span>
<span id="cb29-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(tutoring_fuzzy)</span></code></pre></div></div>
<pre><code>##    id entrance_exam tutoring tutoring_text exit_exam
## 1:  1      92.40833    FALSE      No tutor  78.07592
## 2:  2      72.77238    FALSE      No tutor  58.21757
## 3:  3      53.65090     TRUE         Tutor  61.96543
## 4:  4      98.32688    FALSE      No tutor  67.48956
## 5:  5      69.71219     TRUE         Tutor  54.12888
## 6:  6      68.06771     TRUE         Tutor  60.13143</code></pre>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-econ-3/unnamed-chunk-16-1.png" class="img-fluid"></p>
<p>Check the count and percentages of compliance:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb31" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb31-1">tutoring_fuzzy[, leq70 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">=</span> entrance_exam <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">70</span>]</span>
<span id="cb31-2">tutoring_fuzzy[, .(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">count =</span> .N), by <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'tutoring'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'leq70'</span>)][</span>
<span id="cb31-3">  , per <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(count<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(count)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>), by <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'leq70'</span>][</span>
<span id="cb31-4">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">order</span>(leq70, tutoring)]</span></code></pre></div></div>
<pre><code>##    tutoring leq70 count   per
## 1:    FALSE FALSE   646 84.78
## 2:     TRUE FALSE   116 15.22
## 3:    FALSE  TRUE    36 15.13
## 4:     TRUE  TRUE   202 84.87</code></pre>
<p>This table shows there are 36 students who should participate didn’t while 116 who shouldn’t participate did. The students who shouldn’t participate but did account for about one third of all enrolled students. This is a <strong>fuzzy</strong> design.</p>
<section id="fuzzy-gap" class="level3">
<h3 class="anchored" data-anchor-id="fuzzy-gap">Fuzzy Gap</h3>
<p>First, let’s look at a histogram that shows the probability of being in the tutoring program at different entrance exam scores.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb33" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb33-1">tutoring_fuzzy[, exam_bin <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cut</span>(entrance_exam, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">breaks =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>))]</span>
<span id="cb33-2"></span>
<span id="cb33-3">tutoring_bins <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> tutoring_fuzzy[, .(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">count =</span> .N, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">count_t =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(tutoring), </span>
<span id="cb33-4">                                    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">per =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(tutoring)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>.N)</span>
<span id="cb33-5">                                , by <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'exam_bin'</span>][<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">order</span>(exam_bin)]</span>
<span id="cb33-6"></span>
<span id="cb33-7"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> tutoring_bins, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> exam_bin, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> per)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> </span>
<span id="cb33-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_col</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_vline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xintercept =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">8.5</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb33-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Entrance exam score"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Proportion of students participating in program"</span>)</span></code></pre></div></div>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-econ-3/unnamed-chunk-18-1.png" class="img-fluid"></p>
<p>If this were a sharp design, every single bar to the left of the cut point would be 100% and every single bar to the right would be 0%, but that’s not the case in this fuzzy design.</p>
<ul>
<li>100% of students who scored between 25 and 50 on the entrance exam used tutoring</li>
<li>This rate drops to 80ish% up until the cut point at 70</li>
<li>There’s about 15% chance of using tutoring if students are above the threshold</li>
</ul>
</section>
<section id="discontinuity-in-outcome-1" class="level3">
<h3 class="anchored" data-anchor-id="discontinuity-in-outcome-1">Discontinuity in Outcome</h3>
<p>We can visualize the gap by making scatter plots of running variable against outcome. Moreover, we can fit data with linear and local polynomial regressions on both sides of the threshold.</p>
<p><strong>Fit data with linear regressions</strong></p>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-econ-3/unnamed-chunk-19-1.png" class="img-fluid"></p>
<p><strong>Fit data with local polynomial regressions</strong></p>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-econ-3/unnamed-chunk-20-1.png" class="img-fluid"></p>
</section>
<section id="parametric-and-non-parametric-estimation" class="level3">
<h3 class="anchored" data-anchor-id="parametric-and-non-parametric-estimation">Parametric and Non-parametric Estimation</h3>
<p>Given the compliance issues, we need to isolate causal effects for compliers from others, i.e., the <em>complier average causal effect</em> (<strong>CACE</strong>).</p>
<p>As a result, we need an <strong>instrument</strong> which implies what should have happened rather than what actually happened. In a fuzzy design, the variable indicating if someone is above or below the threshold is a valid instrument.</p>
<p>Particularly, in this example, let “entrance score less than 70”, “participation in tutoring”, and “exit score” be denoted as <img src="https://latex.codecogs.com/png.latex?Z">, <img src="https://latex.codecogs.com/png.latex?X">, and <img src="https://latex.codecogs.com/png.latex?Y">. The indication variable of “entrance score less than 70” satisfies all requirements for a valid instrument:</p>
<ul>
<li>Relevance: The cutoff affects the access to the tutoring program; <img src="https://latex.codecogs.com/png.latex?Z%20%5Crightarrow%20X"> and <img src="https://latex.codecogs.com/png.latex?Cor(Z,%20X)%5Cneq%200">.</li>
<li>Exclusion: The cutoff affects exit exam scores only through the tutoring program; <img src="https://latex.codecogs.com/png.latex?Z%20%5Crightarrow%20X%5Crightarrow%20Y"> and <img src="https://latex.codecogs.com/png.latex?Cor(Z,Y%7CX)=0">.</li>
<li>Exogeneity: Unobserved confounders between the tutoring program and exit exam scores are unrelated to the cutoff in local. For example, IQ is an unobserved variable in the outcome equation. The implicit assumption is that students who scored barely below or above the cutoff have the same level of IQ.</li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb34" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb34-1">tutoring_fuzzy[, entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">=</span> entrance_exam <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">70</span>]</span>
<span id="cb34-2"></span>
<span id="cb34-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Run a regression in a sharp RD design</span></span>
<span id="cb34-4">model_sharp <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(exit_exam <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> tutoring,</span>
<span id="cb34-5">                  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">filter</span>(tutoring_fuzzy,</span>
<span id="cb34-6">                                entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span></span>
<span id="cb34-7">                                  entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>))</span>
<span id="cb34-8"></span>
<span id="cb34-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Run a regression in a fuzzy RD design</span></span>
<span id="cb34-10">model_fuzzy <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> estimatr<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">::</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">iv_robust</span>(exit_exam <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> tutoring <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span></span>
<span id="cb34-11">                                     entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> leq70,</span>
<span id="cb34-12">                                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">filter</span>(tutoring_fuzzy,</span>
<span id="cb34-13">                                                 entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> </span>
<span id="cb34-14">                                                   entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>))</span>
<span id="cb34-15"></span>
<span id="cb34-16"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">modelsummary</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Sharp RD (wrong)"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> model_sharp,</span>
<span id="cb34-17">                  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Fuzzy RD (bw = 10)"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> model_fuzzy),</span>
<span id="cb34-18">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">gof_omit =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"IC|Log|Adj|p</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\\</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">.value|statistic|se_type|RMSE|Std.Errors"</span>,</span>
<span id="cb34-19">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stars =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">output =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"table2.tex"</span>) </span></code></pre></div></div>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-econ-3/table2.png" class="img-fluid"></p>
<p><strong>Note</strong>:</p>
<ul>
<li>We’re estimating a <strong>CACE</strong> or a <em>local average treatment effect</em> (<strong>LATE</strong>) for people in the bandwidth, because we’re working with regression discontinuity.</li>
<li>We’re estimating the CACE/LATE for compliers only, because we’re using instruments.</li>
<li>We <strong>should check the robustness</strong> of estimates by modifying the bandwidth, adding polynomial terms, and others that we discussed in Practice 6.</li>
</ul>
<p>Also, we can estimate the CACE in non-parametric methods. We use the fuzzy argument in <code>rdrobust()</code> to specify the treatment column (or tutoring in our case). Importantly, we do not need to specify an instrument (or even create one!). All you need to specify is the column that indicates treatment status. <code>rdrobust()</code> will do all the above/below-the-cutoff instrument stuff automatically for us.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb35" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb35-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rdrobust</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> tutoring_fuzzy<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>exit_exam, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> tutoring_fuzzy<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>entrance_exam,</span>
<span id="cb35-2">         <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">c =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">70</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fuzzy =</span> tutoring_fuzzy<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>tutoring) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%&gt;%</span></span>
<span id="cb35-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>()</span></code></pre></div></div>
<pre><code>## Call: rdrobust
## 
## Number of Obs.                 1000
## BW type                       mserd
## Kernel                   Triangular
## VCE method                       NN
## 
## Number of Obs.                  238          762
## Eff. Number of Obs.             170          347
## Order est. (p)                    1            1
## Order bias  (q)                   2            2
## BW est. (h)                  12.985       12.985
## BW bias (b)                  19.733       19.733
## rho (h/b)                     0.658        0.658
## Unique Obs.                     238          762
## 
## =============================================================================
##         Method     Coef. Std. Err.         z     P&gt;|z|      [ 95% C.I. ]       
## =============================================================================
##   Conventional     9.683     1.893     5.116     0.000     [5.973 , 13.393]    
##         Robust         -         -     4.258     0.000     [5.210 , 14.095]    
## =============================================================================</code></pre>
<p><strong>Note</strong>:</p>
<ul>
<li>We <strong>should check the robustness</strong> of estimates by modifying the bandwidth (ideal, half, double) and using different kernels (e.g., uniform, triangular, Epanechnikov).</li>
</ul>
<p><strong>Recall</strong>:</p>
<p>There is an alternative way to evaluate an causal effect with ONE instrument in regressions:</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbeta_%7B%5Ctext%7BIV%7D%7D%20=%20%5Cfrac%7B%5Cbeta_%5Ctext%7Breduced%20form%7D%7D%7B%5Cbeta_%5Ctext%7B1st%20stage%7D%7D,%0A"></p>
<p>where the first stage and the reduced form are specified respectively as</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D~%0Ax_%5Ctext%7Bendog%7D%20&amp;=%20%5Cbeta_%5Ctext%7B1st%20stage%7Dz+%20X_%5Ctext%7Bexog%7D'%5Ctheta+%5Ceta,%20%5Ctext%7B%20and%7D%5C%5C%5C%5C%0Ay%20&amp;=%20%5Cbeta_%5Ctext%7Breduced%20form%7Dz+X_%5Ctext%7Bexog%7D'%5Cgamma+%5Cepsilon.%0A%5Cend%7Balign*%7D%0A"></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb37" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb37-1">model_FirstStage <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(tutoring <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> leq70, </span>
<span id="cb37-2">                       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">filter</span>(tutoring_fuzzy, </span>
<span id="cb37-3">                                     entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> </span>
<span id="cb37-4">                                       entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>))</span>
<span id="cb37-5"></span>
<span id="cb37-6">model_Reduced <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(exit_exam <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> leq70, </span>
<span id="cb37-7">                    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">filter</span>(tutoring_fuzzy, </span>
<span id="cb37-8">                                  entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> </span>
<span id="cb37-9">                                    entrance_centered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>))</span>
<span id="cb37-10"></span>
<span id="cb37-11">model_Reduced<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>coef[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'leq70TRUE'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>model_FirstStage<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>coef[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'leq70TRUE'</span>]</span></code></pre></div></div>
<pre><code>## leq70TRUE 
##  9.741044</code></pre>


</section>
</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <guid>https://yanghaowang.github.io/posts/causal-inference-econ-3/</guid>
  <pubDate>Sun, 20 Feb 2022 23:25:26 GMT</pubDate>
</item>
<item>
  <title>Review on Causal Inference (Part 2)</title>
  <link>https://yanghaowang.github.io/posts/causal-inference-econ-2/</link>
  <description><![CDATA[ 






<section id="practice-4-instrumental-variables" class="level2">
<h2 class="anchored" data-anchor-id="practice-4-instrumental-variables">Practice 4: Instrumental Variables</h2>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1">wage <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fread</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"IV/wage2.csv"</span>)</span>
<span id="cb1-2">ed_real <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">na.omit</span>(wage)</span>
<span id="cb1-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">print</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Number of Rows:'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Number of Columns:'</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dim</span>(ed_real)))</span></code></pre></div></div>
<pre><code>## [1] "Number of Rows: 663"   "Number of Columns: 17"</code></pre>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(ed_real)</span></code></pre></div></div>
<pre><code>##    wage hours  IQ KWW educ exper tenure age married black south urban sibs brthord meduc feduc    lwage
## 1:  769    40  93  35   12    11      2  31       1     0     0     1    1       2     8     8 6.645091
## 2:  825    40 108  46   14    11      9  33       1     0     0     1    1       2    14    14 6.715384
## 3:  650    40  96  32   12    13      7  32       1     0     0     1    4       3    12    12 6.476973
## 4:  562    40  74  27   11    14      5  34       1     0     0     1   10       6     6    11 6.331502
## 5:  600    40  91  24   10    13      0  30       0     0     0     1    1       2     8     8 6.396930
## 6: 1154    45 111  37   15    13      1  36       1     0     0     0    2       3    14     5 7.050990</code></pre>
<section id="navie-model" class="level3">
<h3 class="anchored" data-anchor-id="navie-model">Navie Model</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1">model_naive <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(wage <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> educ <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> hours <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> exper <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> tenure <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> age <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> married <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> black <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> </span>
<span id="cb5-2">                    south <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> urban <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> sibs <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> brthord, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> ed_real)</span>
<span id="cb5-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>(model_naive)</span></code></pre></div></div>
<pre><code>## 
## Call:
## lm(formula = wage ~ educ + hours + exper + tenure + age + married + 
##     black + south + urban + sibs + brthord, data = ed_real)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -760.19 -232.71  -47.58  175.86 2030.93 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(&gt;|t|)    
## (Intercept) -393.560    200.607  -1.962 0.050205 .  
## educ          61.384      7.661   8.012 5.22e-15 ***
## hours         -4.205      1.976  -2.128 0.033708 *  
## exper          9.764      4.532   2.154 0.031579 *  
## tenure         3.480      2.954   1.178 0.239141    
## age           10.659      5.575   1.912 0.056326 .  
## married      182.178     47.054   3.872 0.000119 ***
## black       -170.437     54.618  -3.121 0.001885 ** 
## south        -38.523     31.098  -1.239 0.215878    
## urban        192.487     31.701   6.072 2.15e-09 ***
## sibs           4.399      7.983   0.551 0.581767    
## brthord      -22.558     11.694  -1.929 0.054167 .  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 359.3 on 651 degrees of freedom
## Multiple R-squared:  0.2319, Adjusted R-squared:  0.2189 
## F-statistic: 17.87 on 11 and 651 DF,  p-value: &lt; 2.2e-16</code></pre>
</section>
<section id="check-instrument-validity" class="level3">
<h3 class="anchored" data-anchor-id="check-instrument-validity">Check Instrument Validity</h3>
<ol type="1">
<li>Relevance: The instrument is correlated with the endogenous variable</li>
<li>Exclusion: Instrument is correlated with the outcome only through the endogenous variable</li>
<li>Exogeneity: The instrument is exogenous; in other words, it is NOT correlated with omitting variables</li>
</ol>
<p><strong>Relevance</strong></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1">ed_real_long <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">melt</span>(ed_real[, .(educ, feduc, meduc)],</span>
<span id="cb7-2">                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">id.vars =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'educ'</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">measure.vars =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'feduc'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'meduc'</span>),</span>
<span id="cb7-3">                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">variable.name =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'instrument'</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">value.name =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'instrument_val'</span>)</span>
<span id="cb7-4">ed_real_long <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> ed_real_long[, .(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_obs =</span> .N)</span>
<span id="cb7-5">                             , by <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'educ'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'instrument'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'instrument_val'</span>)]</span>
<span id="cb7-6"></span>
<span id="cb7-7"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(ed_real_long, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x=</span>instrument_val, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> educ)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> </span>
<span id="cb7-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size=</span>n_obs), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alpha =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb7-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_smooth</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">weight=</span>n_obs), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'loess'</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">formula =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'y ~ x'</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb7-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_wrap</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vars</span>(instrument))</span></code></pre></div></div>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-econ-2/unnamed-chunk-3-1.png" class="img-fluid"></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1">model_check_instruments <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(educ <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> feduc <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> meduc, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> ed_real)</span>
<span id="cb8-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>(model_check_instruments)</span></code></pre></div></div>
<pre><code>## 
## Call:
## lm(formula = educ ~ feduc + meduc, data = ed_real)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -4.2226 -1.5658 -0.4271  1.7373  5.7305 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(&gt;|t|)    
## (Intercept)  9.91329    0.31959  31.019  &lt; 2e-16 ***
## feduc        0.21894    0.02889   7.578 1.19e-13 ***
## meduc        0.14017    0.03365   4.165 3.52e-05 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1.997 on 660 degrees of freedom
## Multiple R-squared:  0.2015, Adjusted R-squared:  0.1991 
## F-statistic: 83.29 on 2 and 660 DF,  p-value: &lt; 2.2e-16</code></pre>
<p><strong>Exclusion</strong></p>
<ol type="1">
<li>Check the relationship between the instruments and the outcome, i.e., wages (we should see some relationship)</li>
<li>Argue the relationship is built on the path through the endogenous variable, i.e., education</li>
</ol>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1">ed_real_long <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">melt</span>(ed_real[, .(wage, feduc, meduc)],</span>
<span id="cb10-2">                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">id.vars =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'wage'</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">measure.vars =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'feduc'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'meduc'</span>),</span>
<span id="cb10-3">                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">variable.name =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'instrument'</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">value.name =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'instrument_val'</span>)</span>
<span id="cb10-4"></span>
<span id="cb10-5"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(ed_real_long, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x=</span>instrument_val, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> wage)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> </span>
<span id="cb10-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alpha =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_smooth</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'loess'</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">formula =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'y ~ x'</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_wrap</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vars</span>(instrument))</span></code></pre></div></div>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-econ-2/unnamed-chunk-5-1.png" class="img-fluid"></p>
<p><strong>Exogeneity</strong></p>
<p>There’s no statistical test for exogeneity.</p>
<p>Scott Cunningham’s argument</p>
<blockquote class="blockquote">
<p>The reason I think this is because an instrument doesn’t belong in the structural error term and the structural error term is all the intuitive things that determine your outcome. So <em>it must be weird, otherwise it’s probably in the error term.</em></p>
</blockquote>
</section>
<section id="stage-least-squares-2sls" class="level3">
<h3 class="anchored" data-anchor-id="stage-least-squares-2sls">2-Stage Least Squares (2SLS)</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb11-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Conduct 2SLS manually</span></span>
<span id="cb11-2">first_stage <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(educ <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> feduc <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> meduc <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> hours <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> exper <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> tenure <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> age <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb11-3">                    married <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> black <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> south <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> urban <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> sibs <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> brthord, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> ed_real)</span>
<span id="cb11-4">ed_real_with_pred <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">copy</span>(ed_real)</span>
<span id="cb11-5">ed_real_with_pred<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>educ_hat <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> first_stage<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fitted.values</span>
<span id="cb11-6">second_stage <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(wage <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> educ_hat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> hours <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> exper <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> tenure <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> age <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb11-7">                     married <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> black <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> south <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> urban <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> sibs <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> brthord, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> ed_real_with_pred)</span>
<span id="cb11-8"></span>
<span id="cb11-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Conduct 2SLS automatically</span></span>
<span id="cb11-10">model_2sls <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> estimatr<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">::</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">iv_robust</span>(wage <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> educ <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> hours <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> exper <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> tenure <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> age <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> </span>
<span id="cb11-11">                                    married <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> black <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> south <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> urban <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> sibs <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> brthord <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> </span>
<span id="cb11-12">                                    feduc <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> meduc <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> hours <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> exper <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> tenure <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> age <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> </span>
<span id="cb11-13">                                    married <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> black <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> south <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> urban <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> sibs <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> brthord, </span>
<span id="cb11-14">                                  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> ed_real, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">diagnostics =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span></code></pre></div></div>
<p><strong>Summary</strong></p>
<pre><code>## 
## ============================================================
##              Naive OLS    2SLS (Manual)  2SLS (Auto)        
## ------------------------------------------------------------
## (Intercept)  -393.56      -1064.47 ***    -1064.47 *        
##              (200.61)      (302.54)      [-1680.71; -448.23]
## educ           61.38 ***                    127.86 *        
##                (7.66)                    [   83.31;  172.40]
## educ_hat                    127.86 ***                      
##                             (23.35)                         
## ------------------------------------------------------------
## Controls      YES           YES             YES             
## R^2             0.23          0.19            0.14          
## Adj. R^2        0.22          0.18            0.13          
## Num. obs.     663           663             663             
## RMSE                                        379.48          
## ============================================================
## *** p &lt; 0.001; ** p &lt; 0.01; * p &lt; 0.05 (or Null hypothesis value outside the confidence interval).</code></pre>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb13-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>(model_2sls)</span></code></pre></div></div>
<pre><code>## 
## Call:
## estimatr::iv_robust(formula = wage ~ educ + hours + exper + tenure + 
##     age + married + black + south + urban + sibs + brthord | 
##     feduc + meduc + hours + exper + tenure + age + married + 
##         black + south + urban + sibs + brthord, data = ed_real, 
##     diagnostics = TRUE)
## 
## Standard error type:  HC2 
## 
## Coefficients:
##              Estimate Std. Error t value  Pr(&gt;|t|)  CI Lower CI Upper  DF
## (Intercept) -1064.471    313.829 -3.3919 7.362e-04 -1680.709 -448.232 651
## educ          127.858     22.686  5.6360 2.594e-08    83.311  172.404 651
## hours          -4.416      2.780 -1.5885 1.127e-01    -9.875    1.043 651
## exper          30.677      8.439  3.6352 2.997e-04    14.106   47.248 651
## tenure          1.976      3.103  0.6366 5.246e-01    -4.118    8.069 651
## age            -4.171      8.052 -0.5180 6.046e-01   -19.982   11.640 651
## married       195.132     47.632  4.0967 4.720e-05   101.602  288.663 651
## black        -148.117     47.498 -3.1184 1.898e-03  -241.385  -54.850 651
## south         -32.697     33.067 -0.9888 3.231e-01   -97.627   32.233 651
## urban         167.666     31.920  5.2527 2.033e-07   104.988  230.345 651
## sibs           12.351      8.757  1.4104 1.589e-01    -4.845   29.547 651
## brthord       -16.887     11.608 -1.4547 1.462e-01   -39.681    5.907 651
## 
## Multiple R-squared:  0.143 , Adjusted R-squared:  0.1286 
## F-statistic: 16.88 on 11 and 651 DF,  p-value: &lt; 2.2e-16
## 
## Diagnostics:
##                  numdf dendf  value  p.value    
## Weak instruments     2   650 42.896  &lt; 2e-16 ***
## Wu-Hausman           1   650 11.659 0.000679 ***
## Overidentifying      1    NA  0.104 0.747148    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1</code></pre>
<p><strong>Notes</strong>: A test of overidentifying restrictions regresses the residuals <img src="https://latex.codecogs.com/png.latex?u"> from an IV or 2SLS regression on all instruments in <img src="https://latex.codecogs.com/png.latex?z">. Under the <strong>null</strong> hypothesis, all instruments are uncorrelated with <img src="https://latex.codecogs.com/png.latex?u">.</p>
<p>The test of overidentifying restrictions should be performed routinely in any overidentified model estimated with instrumental variables techniques. Instrumental variables techniques are powerful, but if a strong rejection of the null hypothesis is encountered, you should strongly doubt the validity of the estimates.</p>
</section>
</section>
<section id="practice-5-complier-average-treatment-effects" class="level2">
<h2 class="anchored" data-anchor-id="practice-5-complier-average-treatment-effects">Practice 5: Complier Average Treatment Effects</h2>
<p>We can calculate conditional average treatment effect (CATE) by averaging the treatment effect of a program over some segment of the population.</p>
<p>One important type of CATE is the effect of a program on just those who comply with the program. This is the complier average treatment effect, but the acronym would be the same as the conditional average treatment effect, so we call it the <strong>complier average causal effect</strong> (<strong>CACE</strong>), also known as the local average treatment effect (LATE).</p>
<p>We can split the population into four types of people:</p>
<ul>
<li><strong>Compliers</strong>: People who follow whatever their assignment is</li>
<li><strong>Always takers</strong>: People who will receive or seek out the treatment regardless of assignment</li>
<li><strong>Never takers</strong>: People who will NOT receive or seek out the treatment regardless of assignment</li>
<li><strong>Defiers</strong>: People who will do the opposite of whatever their assignment is</li>
</ul>
<p>For simplicity, we assume that defiers don’t exist based on the idea of <em>monotonicity</em>, which means that the effect of being assigned to treatment only increases the likelihood of participating in the program rather than decreases.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb15-1">bed_nets_time_machine <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fread</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ITT&amp;CACE/bed_nets_time_machine.csv"</span>)</span></code></pre></div></div>
<p>Ideally, we can identify different types of people from the data. <img src="https://yanghaowang.github.io/posts/causal-inference-econ-2/unnamed-chunk-10-1.png" class="img-fluid"></p>
<p>However, we can tell some of the always takers from the control group (those who used bed nets after being assigned to the control group) and some of the never takers from the treatment group (those who did not use a bed net after being assigned to the treatment group), but compliers are mixed up with the always and never takers. <img src="https://yanghaowang.github.io/posts/causal-inference-econ-2/unnamed-chunk-11-1.png" class="img-fluid"></p>
<section id="intent-to-treat-itt" class="level3">
<h3 class="anchored" data-anchor-id="intent-to-treat-itt">Intent to Treat (ITT)</h3>
<p>We can calculate ITT by assuming the proportion of compliers (c), never takers (n), and always takers (a) are equally spread across treatment and control. This assumption is plausible in a randomized control trial.</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D~%0A%5Ctext%7BITT%7D%5Cspace=%5Cspace&amp;%20%5Csum_%7Bk%5Cin%5C%5C%7Bc,n,a%5C%5C%7D%7D%5Cpi_k%5Ctimes(%5Ctext%7BT%7D-%5Ctext%7BC%7D)_k%0A%5Cend%7Balign*%7D%0A"></p>
<p>Suppose treatment doesn’t make someone more likely to be an always taker or a never taker, we have <img src="https://latex.codecogs.com/png.latex?%5Ctext%7BATACE%7D=0"> and <img src="https://latex.codecogs.com/png.latex?%5Ctext%7BNTACE%7D=0">. Hence,</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Ctext%7BITT%7D=%5Cpi_c%5Ctext%7BCACE%7D%20%5Cimplies%20%5Ctext%7BCACE%7D%20=%20%5Cfrac%7B%5Ctext%7BITT%7D%7D%7B%5Cpi_c%7D%0A"></p>
<p><strong>Finding ITT Using regression</strong></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb16-1">itt_model <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(health <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> treatment, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> bed_nets_time_machine)</span>
<span id="cb16-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>(itt_model)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>coeff <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%&gt;%</span></span>
<span id="cb16-3">  (<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(x, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>))</span></code></pre></div></div>
<pre><code>##                    Estimate Std. Error t value Pr(&gt;|t|)
## (Intercept)         40.9381     0.4444 92.1143        0
## treatmentTreatment   5.9880     0.6298  9.5081        0</code></pre>
</section>
<section id="cacelate" class="level3">
<h3 class="anchored" data-anchor-id="cacelate">CACE/LATE</h3>
<p>Given$ $, we can calculate <img src="https://latex.codecogs.com/png.latex?%5Ctext%7BCACE/LATE%7D"> by obtaining <img src="https://latex.codecogs.com/png.latex?%5Cpi_c">.</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D~%0A%5Cpi_a+%5Cpi_c%20&amp;=%20%5Ctext%7Bpercent%20of%20yes%20in%20treatment%7D%20%5C%5C%5C%5C%0A%5Cimplies%20%5Cpi_c&amp;=%5Ctext%7Bpercent%20of%20yes%20in%20treatment%7D%20-%20%5Cpi_a%0A%5C%5C%5C%5C%20&amp;=%5Ctext%7Bpercent%20of%20yes%20in%20treatment%7D%20-%20%5Ctext%7Bpercent%20of%20yes%20in%20control%7D%0A%5Cend%7Balign*%7D%0A"></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb18-1">table_net <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> bed_nets_time_machine[, .N, by<span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'treatment'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'bed_net'</span>)][</span>
<span id="cb18-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">order</span>(treatment, bed_net)]</span>
<span id="cb18-3">table_net[, percent<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">=</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(N<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(N), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>), by<span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'treatment'</span>]</span>
<span id="cb18-4">table_net</span></code></pre></div></div>
<pre><code>##    treatment    bed_net   N percent
## 1:   Control    Bed net 196  0.1952
## 2:   Control No bed net 808  0.8048
## 3: Treatment    Bed net 608  0.6104
## 4: Treatment No bed net 388  0.3896</code></pre>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb20" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb20-1">cACE <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> itt_model<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>coef[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"treatmentTreatment"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> </span>
<span id="cb20-2">  (table_net[treatment <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Treatment'</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> bed_net <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Bed net'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>percent <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> </span>
<span id="cb20-3">     table_net[treatment <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Control'</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> bed_net <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Bed net'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>percent)</span>
<span id="cb20-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(cACE) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"CACE"</span></span>
<span id="cb20-5"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(cACE, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<pre><code>##  CACE 
## 14.42</code></pre>
<section id="iv-regression" class="level4">
<h4 class="anchored" data-anchor-id="iv-regression">IV Regression</h4>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb22" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb22-1">model_2sls <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> estimatr<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">::</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">iv_robust</span>(health <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.factor</span>(bed_net) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.factor</span>(treatment),</span>
<span id="cb22-2">                                  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> bed_nets_time_machine)</span>
<span id="cb22-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>(model_2sls)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>coef, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<pre><code>##                              Estimate Std. Error t value Pr(&gt;|t|) CI Lower
## (Intercept)                     52.54       0.84    62.2        0    50.89
## as.factor(bed_net)No bed net   -14.42       1.25   -11.5        0   -16.88
##                              CI Upper   DF
## (Intercept)                     54.20 1998
## as.factor(bed_net)No bed net   -11.96 1998</code></pre>


</section>
</section>
</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Causal</category>
  <category>Causal-IV</category>
  <category>Causal-CACE/LATE</category>
  <guid>https://yanghaowang.github.io/posts/causal-inference-econ-2/</guid>
  <pubDate>Sat, 12 Feb 2022 19:38:15 GMT</pubDate>
</item>
<item>
  <title>Review on Causal Inference (Part 1)</title>
  <link>https://yanghaowang.github.io/posts/causal-inference-econ-1/</link>
  <description><![CDATA[ 






<section id="practice-1-ates-and-cates" class="level2">
<h2 class="anchored" data-anchor-id="practice-1-ates-and-cates">Practice 1: ATEs and CATEs</h2>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Examine the effect of private school on earnings</span></span>
<span id="cb1-2">schools <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fread</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ATEs&amp;CTEs/public_private_earnings.csv"</span>)</span>
<span id="cb1-3">schools</span></code></pre></div></div>
<pre><code>##    student_id group   ivy1   ivy2  ivy3 public1 public2 public3 enrolled earnings
## 1:          1     A   &lt;NA&gt; Reject Admit    &lt;NA&gt;   Admit    &lt;NA&gt;     ivy3   110000
## 2:          2     A   &lt;NA&gt; Reject Admit    &lt;NA&gt;   Admit    &lt;NA&gt;     ivy3   100000
## 3:          3     A   &lt;NA&gt; Reject Admit    &lt;NA&gt;   Admit    &lt;NA&gt;  public2   110000
## 4:          4     B  Admit   &lt;NA&gt;  &lt;NA&gt;   Admit    &lt;NA&gt;   Admit     ivy1    60000
## 5:          5     B  Admit   &lt;NA&gt;  &lt;NA&gt;   Admit    &lt;NA&gt;   Admit  public3    30000
## 6:          6     C   &lt;NA&gt;  Admit  &lt;NA&gt;    &lt;NA&gt;    &lt;NA&gt;    &lt;NA&gt;     ivy2   115000
## 7:          7     C   &lt;NA&gt;  Admit  &lt;NA&gt;    &lt;NA&gt;    &lt;NA&gt;    &lt;NA&gt;     ivy2    75000
## 8:          8     D Reject   &lt;NA&gt;  &lt;NA&gt;   Admit   Admit    &lt;NA&gt;  public1    90000
## 9:          9     D Reject   &lt;NA&gt;  &lt;NA&gt;   Admit   Admit    &lt;NA&gt;  public2    60000</code></pre>
<ul>
<li><p>Select comparable groups</p></li>
<li><p>Evaluate ATEs</p>
<ul>
<li><p>Manual Calculation</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Ctext%7BATE%7D=%5Csum_i%20%5Cpi_i%5Ctimes%20%5Ctext%7BCATE%7D_i%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Cpi_i"> is the share of group <img src="https://latex.codecogs.com/png.latex?i"> and <img src="https://latex.codecogs.com/png.latex?%5Ctext%7BCATE%7D_i"> is the conditional ATE of observations in group <img src="https://latex.codecogs.com/png.latex?i">.</p></li>
<li><p>Regression</p></li>
</ul></li>
</ul>
<section id="manual-calculation" class="level3">
<h3 class="anchored" data-anchor-id="manual-calculation">Manual Calculation</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1">schools[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">':='</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">private =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grepl</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ivy'</span>, enrolled))]</span>
<span id="cb3-2">schools[group <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%in%</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'A'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'B'</span>)][, .(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_obs =</span> .N, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">avg_earnings =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(earnings))</span>
<span id="cb3-3">                                , by<span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'group'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'private'</span>)]</span></code></pre></div></div>
<pre><code>##    group private n_obs avg_earnings
## 1:     A    TRUE     2       105000
## 2:     A   FALSE     1       110000
## 3:     B    TRUE     1        60000
## 4:     B   FALSE     1        30000</code></pre>
</section>
<section id="regression" class="level3">
<h3 class="anchored" data-anchor-id="regression">Regression</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(earnings <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> private <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(group), </span>
<span id="cb5-2">   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data=</span>schools[group <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%in%</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'A'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'B'</span>)])</span></code></pre></div></div>
<pre><code>## 
## Call:
## lm(formula = earnings ~ private + factor(group), data = schools[group %in% 
##     c("A", "B")])
## 
## Coefficients:
##    (Intercept)     privateTRUE  factor(group)B  
##         100000           10000          -60000</code></pre>
</section>
</section>
<section id="practice-2-matching-and-inverse-probability-weighting" class="level2">
<h2 class="anchored" data-anchor-id="practice-2-matching-and-inverse-probability-weighting">Practice 2: Matching and Inverse Probability Weighting</h2>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Examine the effect of bed net usage on malaria risk</span></span>
<span id="cb7-2">nets <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fread</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Matching&amp;IPW/mosquito_nets.csv"</span>)</span>
<span id="cb7-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(nets)</span></code></pre></div></div>
<pre><code>##    id   net net_num malaria_risk income health household eligible temperature resistance
## 1:  1  TRUE       1           33    781     56         2    FALSE        21.1         59
## 2:  2 FALSE       0           42    974     57         4    FALSE        26.5         73
## 3:  3 FALSE       0           80    502     15         3    FALSE        25.6         65
## 4:  4  TRUE       1           34    671     20         5     TRUE        21.3         46
## 5:  5 FALSE       0           44    728     17         5    FALSE        19.2         54
## 6:  6 FALSE       0           25   1050     48         1    FALSE        25.3         34</code></pre>
<section id="directed-acyclic-graph-dag" class="level3">
<h3 class="anchored" data-anchor-id="directed-acyclic-graph-dag">Directed Acyclic Graph (DAG)</h3>
<ul>
<li><p>Identify mediator, confounder, and collider</p>
<ul>
<li><p>Example <img src="https://yanghaowang.github.io/posts/causal-inference-econ-1/unnamed-chunk-5-1.png" class="img-fluid"></p></li>
<li><p>DAG for nets</p>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-econ-1/dag-1.png" class="img-fluid"></p>
<ul>
<li>Control variables?</li>
<li>Do we need to control <code>eligible</code> and <code>household</code></li>
</ul></li>
</ul></li>
</ul>
<section id="conditional-independence" class="level4">
<h4 class="anchored" data-anchor-id="conditional-independence">Conditional Independence</h4>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?%5Ctext%7BHealth%7D%5Cperp%5Ctext%7BNumb.%20of%20Household%7D"></li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cor</span>(nets<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>health, nets<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>household)</span></code></pre></div></div>
<pre><code>## [1] 9.785337e-05</code></pre>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?%5Ctext%7BIncome%7D%5Cperp%5Ctext%7BInsect%20Resistance%7D"></li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb11-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cor</span>(nets<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>income, nets<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>resistance)</span></code></pre></div></div>
<pre><code>## [1] 0.01371297</code></pre>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?%5Ctext%7BMalaria%20risk%7D%5Cperp%5Ctext%7BNumb.%20of%20Household%7D%20%5Cmid%20%5Ctext%7B(Net%20Use,%20Health,%20Income,%20Temp)%7D"></li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb13-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(malaria_risk <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> household <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> net <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> health <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> income <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> temperature,</span>
<span id="cb13-2">   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> nets) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%&gt;%</span></span>
<span id="cb13-3">  (<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>(x)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>coeff) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%&gt;%</span></span>
<span id="cb13-4">  (<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(x, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>))</span></code></pre></div></div>
<pre><code>##             Estimate Std. Error  t value Pr(&gt;|t|)
## (Intercept)  76.2067     0.9658  78.9062   0.0000
## household    -0.0155     0.0893  -0.1730   0.8626
## netTRUE     -10.4370     0.2665 -39.1633   0.0000
## health        0.1483     0.0107  13.8997   0.0000
## income       -0.0751     0.0010 -72.5635   0.0000
## temperature   1.0058     0.0310  32.4829   0.0000</code></pre>
<p><strong>Notes:</strong> No correlation ⇏ Independence</p>
<blockquote class="blockquote">
<p>[Example] Flip a fair coin to determine the amount of your bet: bet $1 if heads \$2 if tails. Then flip again: win the amount of your bet if heads lose if tails.</p>
</blockquote>
</section>
</section>
<section id="naive-comparison" class="level3">
<h3 class="anchored" data-anchor-id="naive-comparison">Naive Comparison</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb15-1">model_naive <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(malaria_risk <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> net, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> nets) </span>
<span id="cb15-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>(model_naive)</span></code></pre></div></div>
<pre><code>## 
## Call:
## lm(formula = malaria_risk ~ net, data = nets)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -26.937  -9.605  -1.937   7.063  55.395 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(&gt;|t|)    
## (Intercept)  41.9365     0.4049  103.57   &lt;2e-16 ***
## netTRUE     -16.3315     0.6495  -25.15   &lt;2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 13.25 on 1750 degrees of freedom
## Multiple R-squared:  0.2654, Adjusted R-squared:  0.265 
## F-statistic: 632.3 on 1 and 1750 DF,  p-value: &lt; 2.2e-16</code></pre>
<section id="balance-check" class="level4">
<h4 class="anchored" data-anchor-id="balance-check">Balance Check</h4>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb17-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (v <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'income'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'temperature'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'health'</span>)) {</span>
<span id="cb17-2">  plot_command <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ggplot(data = nets, aes(x ='</span>, v,</span>
<span id="cb17-3">                         <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">', fill=net)) +geom_density(alpha = 0.7)'</span>)</span>
<span id="cb17-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">print</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">eval</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">parse</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text =</span> plot_command)))</span>
<span id="cb17-5">  test_result <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t.test</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.formula</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(v, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'~net'</span>)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data=</span>nets)</span>
<span id="cb17-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">print</span>(test_result)</span>
<span id="cb17-7">}</span></code></pre></div></div>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-econ-1/unnamed-chunk-10-1.png" class="img-fluid"></p>
<pre><code>## 
##  Welch Two Sample t-test
## 
## data:  income by net
## t = -8.8113, df = 1284.7, p-value &lt; 2.2e-16
## alternative hypothesis: true difference in means between group FALSE and group TRUE is not equal to 0
## 95 percent confidence interval:
##  -100.79660  -64.08593
## sample estimates:
## mean in group FALSE  mean in group TRUE 
##            872.7526            955.1938</code></pre>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-econ-1/unnamed-chunk-10-2.png" class="img-fluid"></p>
<pre><code>## 
##  Welch Two Sample t-test
## 
## data:  temperature by net
## t = 3.492, df = 1404.3, p-value = 0.0004943
## alternative hypothesis: true difference in means between group FALSE and group TRUE is not equal to 0
## 95 percent confidence interval:
##  0.3098586 1.1042309
## sample estimates:
## mean in group FALSE  mean in group TRUE 
##            24.08796            23.38091</code></pre>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-econ-1/unnamed-chunk-10-3.png" class="img-fluid"></p>
<pre><code>## 
##  Welch Two Sample t-test
## 
## data:  health by net
## t = -7.6447, df = 1346.9, p-value = 3.961e-14
## alternative hypothesis: true difference in means between group FALSE and group TRUE is not equal to 0
## 95 percent confidence interval:
##  -8.610309 -5.093693
## sample estimates:
## mean in group FALSE  mean in group TRUE 
##            48.05696            54.90896</code></pre>
</section>
</section>
<section id="regression-1" class="level3">
<h3 class="anchored" data-anchor-id="regression-1">Regression</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb21-1">model_regression <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(malaria_risk <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> net <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> income <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> temperature <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> health, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> nets)</span>
<span id="cb21-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>(model_regression)</span></code></pre></div></div>
<pre><code>## 
## Call:
## lm(formula = malaria_risk ~ net + income + temperature + health, 
##     data = nets)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -13.143  -3.915  -0.561   3.333  16.461 
## 
## Coefficients:
##               Estimate Std. Error t value Pr(&gt;|t|)    
## (Intercept)  76.159901   0.926835   82.17   &lt;2e-16 ***
## netTRUE     -10.441932   0.264906  -39.42   &lt;2e-16 ***
## income       -0.075144   0.001035  -72.58   &lt;2e-16 ***
## temperature   1.005855   0.030953   32.50   &lt;2e-16 ***
## health        0.148362   0.010668   13.91   &lt;2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 5.244 on 1747 degrees of freedom
## Multiple R-squared:  0.8852, Adjusted R-squared:  0.8849 
## F-statistic:  3366 on 4 and 1747 DF,  p-value: &lt; 2.2e-16</code></pre>
</section>
<section id="matching-mahalanobis-distance" class="level3">
<h3 class="anchored" data-anchor-id="matching-mahalanobis-distance">Matching (Mahalanobis Distance)</h3>
<ul>
<li><p>Mahalanobis distance between <img src="https://latex.codecogs.com/png.latex?%5Cbf%7Bx%7D"> and <img src="https://latex.codecogs.com/png.latex?%5Cbf%7By%7D"></p>
<p><img src="https://latex.codecogs.com/png.latex?%0A(%5Cbf%7Bx%7D%20-%20%5Cbf%7By%7D)%5CSigma%5E%7B-1%7D(%5Cbf%7Bx%7D%20-%20%5Cbf%7By%7D)%5ET%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5CSigma"> is the covariance matrix.</p></li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb23" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb23-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(MatchIt)</span>
<span id="cb23-2"></span>
<span id="cb23-3">matched <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matchit</span>(net <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> income <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> temperature <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> health, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> nets,</span>
<span id="cb23-4">                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nearest"</span>, </span>
<span id="cb23-5">                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">distance =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mahalanobis"</span>, </span>
<span id="cb23-6">                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">replace =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb23-7">matched</span></code></pre></div></div>
<pre><code>## A matchit object
##  - method: 1:1 nearest neighbor matching with replacement
##  - distance: Mahalanobis
##  - number of obs.: 1752 (original), 1120 (matched)
##  - target estimand: ATT
##  - covariates: income, temperature, health</code></pre>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb25" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb25-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Dimension of the data used for matching</span></span>
<span id="cb25-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dim</span>(matched<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>X)</span></code></pre></div></div>
<pre><code>## [1] 1752    3</code></pre>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb27" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb27-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Number of the treated</span></span>
<span id="cb27-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(matched<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>treat)</span></code></pre></div></div>
<pre><code>## [1] 681</code></pre>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb29" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb29-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Number of the matched control</span></span>
<span id="cb29-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(matched<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>weights<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span></code></pre></div></div>
<pre><code>## [1] 1120</code></pre>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb31" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb31-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Number of the unmatched control</span></span>
<span id="cb31-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(matched<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>weights<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span></code></pre></div></div>
<pre><code>## [1] 632</code></pre>
<ul>
<li>The <code>matchit()</code> function determines the pair weights by measuring how close the matched pair are. The weights can be used in the regression to account for the variation in distance.</li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb33" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb33-1">nets_matched <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">match.data</span>(matched)</span>
<span id="cb33-2">model_matched <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(malaria_risk <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> net, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> nets_matched, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">weights =</span> weights)</span>
<span id="cb33-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>(model_matched)</span></code></pre></div></div>
<pre><code>## 
## Call:
## lm(formula = malaria_risk ~ net, data = nets_matched, weights = weights)
## 
## Weighted Residuals:
##     Min      1Q  Median      3Q     Max 
## -36.312  -7.605  -1.681   5.395  55.395 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(&gt;|t|)    
## (Intercept)  36.0940     0.5951   60.65   &lt;2e-16 ***
## netTRUE     -10.4890     0.7632  -13.74   &lt;2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 12.47 on 1118 degrees of freedom
## Multiple R-squared:  0.1445, Adjusted R-squared:  0.1438 
## F-statistic: 188.9 on 1 and 1118 DF,  p-value: &lt; 2.2e-16</code></pre>
<section id="balance-check-1" class="level4">
<h4 class="anchored" data-anchor-id="balance-check-1">Balance Check</h4>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb35" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb35-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (v <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'income'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'temperature'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'health'</span>)) {</span>
<span id="cb35-2">  test_result <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t.test</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.formula</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(v, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'~net'</span>)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data=</span>nets_matched)</span>
<span id="cb35-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">print</span>(test_result)</span>
<span id="cb35-4">}</span></code></pre></div></div>
<pre><code>## 
##  Welch Two Sample t-test
## 
## data:  income by net
## t = -3.5017, df = 990.87, p-value = 0.0004829
## alternative hypothesis: true difference in means between group FALSE and group TRUE is not equal to 0
## 95 percent confidence interval:
##  -64.12955 -18.06677
## sample estimates:
## mean in group FALSE  mean in group TRUE 
##            914.0957            955.1938 
## 
## 
##  Welch Two Sample t-test
## 
## data:  temperature by net
## t = 0.79239, df = 952.76, p-value = 0.4283
## alternative hypothesis: true difference in means between group FALSE and group TRUE is not equal to 0
## 95 percent confidence interval:
##  -0.2955968  0.6959627
## sample estimates:
## mean in group FALSE  mean in group TRUE 
##            23.58109            23.38091 
## 
## 
##  Welch Two Sample t-test
## 
## data:  health by net
## t = -3.0287, df = 977.39, p-value = 0.002521
## alternative hypothesis: true difference in means between group FALSE and group TRUE is not equal to 0
## 95 percent confidence interval:
##  -5.567087 -1.189325
## sample estimates:
## mean in group FALSE  mean in group TRUE 
##            51.53075            54.90896</code></pre>
</section>
</section>
<section id="matching-propensity-score" class="level3">
<h3 class="anchored" data-anchor-id="matching-propensity-score">Matching (Propensity Score)</h3>
<p><strong>Other Source</strong>：<a href="https://sejdemyr.github.io/r-tutorials/statistics/tutorial8.html">Simon Ejdemyr’s notes on propensity score matching</a></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb37" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb37-1">matched_psm <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matchit</span>(net <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> income <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> temperature <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> health, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> nets,</span>
<span id="cb37-2">                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nearest"</span>,</span>
<span id="cb37-3">                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">replace =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb37-4">matched_psm</span></code></pre></div></div>
<pre><code>## A matchit object
##  - method: 1:1 nearest neighbor matching with replacement
##  - distance: Propensity score
##              - estimated with logistic regression
##  - number of obs.: 1752 (original), 1098 (matched)
##  - target estimand: ATT
##  - covariates: income, temperature, health</code></pre>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb39" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb39-1">nets_matched_psm <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">match.data</span>(matched_psm)</span>
<span id="cb39-2">model_matched_psm <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(malaria_risk <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> net, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> nets_matched_psm, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">weights =</span> weights)</span>
<span id="cb39-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>(model_matched_psm)</span></code></pre></div></div>
<pre><code>## 
## Call:
## lm(formula = malaria_risk ~ net, data = nets_matched_psm, weights = weights)
## 
## Weighted Residuals:
##     Min      1Q  Median      3Q     Max 
## -57.745  -7.605  -1.605   5.395  59.226 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(&gt;|t|)    
## (Intercept)  36.3025     0.6187   58.67   &lt;2e-16 ***
## netTRUE     -10.6975     0.7857  -13.62   &lt;2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 12.63 on 1096 degrees of freedom
## Multiple R-squared:  0.1447, Adjusted R-squared:  0.1439 
## F-statistic: 185.4 on 1 and 1096 DF,  p-value: &lt; 2.2e-16</code></pre>
<section id="common-support" class="level4">
<h4 class="anchored" data-anchor-id="common-support">Common Support</h4>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb41" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb41-1">model_treatment <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(net <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> income <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> temperature <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> health, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> nets,</span>
<span id="cb41-2">                       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">binomial</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">link =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"logit"</span>))</span>
<span id="cb41-3">nets_pred <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">copy</span>(nets)</span>
<span id="cb41-4">nets_pred<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>pred <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> model_treatment<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fitted.values</span>
<span id="cb41-5"></span>
<span id="cb41-6"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> nets_pred, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> pred, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill=</span>net)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> </span>
<span id="cb41-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_histogram</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"identity"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alpha =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">bins =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">xlim</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> </span>
<span id="cb41-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title=</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Full Sample (N = '</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(nets_pred), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">')'</span>))</span></code></pre></div></div>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-econ-1/unnamed-chunk-17-1.png" class="img-fluid"></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb42" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb42-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> nets_pred[id <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%in%</span> nets_matched_psm<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>id], <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> pred, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill=</span>net)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> </span>
<span id="cb42-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_histogram</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"identity"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alpha =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">bins =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">xlim</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> </span>
<span id="cb42-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title=</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Matched Sample (N = '</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(nets_matched_psm), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">')'</span>))</span></code></pre></div></div>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-econ-1/unnamed-chunk-18-1.png" class="img-fluid"></p>
</section>
<section id="balance-check-2" class="level4">
<h4 class="anchored" data-anchor-id="balance-check-2">Balance Check</h4>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb43" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb43-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (v <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'income'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'temperature'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'health'</span>)) {</span>
<span id="cb43-2">  plot_command <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ggplot(data = nets_matched_psm, aes(x ='</span>, v,</span>
<span id="cb43-3">                         <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">', fill=net)) +geom_density(alpha = 0.7)'</span>)</span>
<span id="cb43-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">print</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">eval</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">parse</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text =</span> plot_command)))</span>
<span id="cb43-5">  test_result <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t.test</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.formula</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(v, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'~net'</span>)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data=</span>nets_matched_psm)</span>
<span id="cb43-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">print</span>(test_result)</span>
<span id="cb43-7">}</span></code></pre></div></div>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-econ-1/unnamed-chunk-19-1.png" class="img-fluid"></p>
<pre><code>## 
##  Welch Two Sample t-test
## 
## data:  income by net
## t = -3.548, df = 954.79, p-value = 0.0004071
## alternative hypothesis: true difference in means between group FALSE and group TRUE is not equal to 0
## 95 percent confidence interval:
##  -64.64167 -18.59971
## sample estimates:
## mean in group FALSE  mean in group TRUE 
##            913.5731            955.1938</code></pre>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-econ-1/unnamed-chunk-19-2.png" class="img-fluid"></p>
<pre><code>## 
##  Welch Two Sample t-test
## 
## data:  temperature by net
## t = 1.4522, df = 910.52, p-value = 0.1468
## alternative hypothesis: true difference in means between group FALSE and group TRUE is not equal to 0
## 95 percent confidence interval:
##  -0.1294926  0.8664727
## sample estimates:
## mean in group FALSE  mean in group TRUE 
##            23.74940            23.38091</code></pre>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-econ-1/unnamed-chunk-19-3.png" class="img-fluid"></p>
<pre><code>## 
##  Welch Two Sample t-test
## 
## data:  health by net
## t = -2.1015, df = 920.12, p-value = 0.03587
## alternative hypothesis: true difference in means between group FALSE and group TRUE is not equal to 0
## 95 percent confidence interval:
##  -4.6145611 -0.1577902
## sample estimates:
## mean in group FALSE  mean in group TRUE 
##            52.52278            54.90896</code></pre>
</section>
</section>
<section id="inverse-probability-weighting" class="level3">
<h3 class="anchored" data-anchor-id="inverse-probability-weighting">Inverse Probability Weighting</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb47" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb47-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Predict the probability of a household using bed nets</span></span>
<span id="cb47-2">model_treatment <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(net <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> income <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> temperature <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> health, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> nets,</span>
<span id="cb47-3">                       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">binomial</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">link =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"logit"</span>))</span>
<span id="cb47-4">nets_ipw <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">copy</span>(nets)</span>
<span id="cb47-5">nets_ipw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>pred <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> model_treatment<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fitted.values</span>
<span id="cb47-6">nets_ipw[, ipw <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">=</span> (net_num <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> pred) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> net_num) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> pred)]</span>
<span id="cb47-7"></span>
<span id="cb47-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Evaluate the effect with inverse probability weights</span></span>
<span id="cb47-9">model_ipw <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(malaria_risk <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> net, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> nets_ipw, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">weights =</span> ipw)</span>
<span id="cb47-10"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>(model_ipw)</span></code></pre></div></div>
<pre><code>## 
## Call:
## lm(formula = malaria_risk ~ net, data = nets_ipw, weights = ipw)
## 
## Weighted Residuals:
##     Min      1Q  Median      3Q     Max 
## -45.705 -14.622  -4.924  10.791 162.642 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(&gt;|t|)    
## (Intercept)  39.6788     0.4684   84.71   &lt;2e-16 ***
## netTRUE     -10.1312     0.6583  -15.39   &lt;2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 19.54 on 1750 degrees of freedom
## Multiple R-squared:  0.1192, Adjusted R-squared:  0.1187 
## F-statistic: 236.8 on 1 and 1750 DF,  p-value: &lt; 2.2e-16</code></pre>
<ul>
<li><p>Inverse Probability Weights</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cfrac%7B%5Ctext%7BTreatment%7D%7D%7B%5Ctext%7BPropensity%7D%7D+%5Cfrac%7B1-%5Ctext%7BTreatment%7D%7D%7B1-%5Ctext%7BPropensity%7D%7D%0A"></p>
<p>Think of this formula in a controlled experiment scenario:</p>
<ul>
<li><p>Individuals are more likely to be <strong>never-takers</strong> (in a control group) if their likelihood values of receiving treatment are lower than the average and they do <em>not</em> receive treatment</p></li>
<li><p>Individuals are more likely to be <strong>always-takers</strong> (in a treatment group) if their likelihood values of receiving treatment are higher than the average and they <em>do</em> receive treatment</p></li>
<li><p>Individuals are more likely to be <strong>compliers</strong> (in both the control and the treatment group) if their likelihood values of receiving treatment are inconsistent with their actual treatment</p></li>
</ul></li>
</ul>
<p>To the end, we evaluate the change in the compliers’ outcomes due to their different exposures to the treatment.</p>
</section>
<section id="results" class="level3">
<h3 class="anchored" data-anchor-id="results">Results</h3>
<pre><code>## 
## ===============================================================================
##              Naive        Regression   Matching (M)  Matching (PS)  IPW        
## -------------------------------------------------------------------------------
## (Intercept)    41.94 ***    76.16 ***    36.09 ***     36.30 ***      39.68 ***
##                (0.40)       (0.93)       (0.60)        (0.62)         (0.47)   
## netTRUE       -16.33 ***   -10.44 ***   -10.49 ***    -10.70 ***     -10.13 ***
##                (0.65)       (0.26)       (0.76)        (0.79)         (0.66)   
## income                      -0.08 ***                                          
##                             (0.00)                                             
## temperature                  1.01 ***                                          
##                             (0.03)                                             
## health                       0.15 ***                                          
##                             (0.01)                                             
## -------------------------------------------------------------------------------
## R^2             0.27         0.89         0.14          0.14           0.12    
## Adj. R^2        0.27         0.88         0.14          0.14           0.12    
## Num. obs.    1752         1752         1120          1098           1752       
## ===============================================================================
## *** p &lt; 0.001; ** p &lt; 0.01; * p &lt; 0.05</code></pre>
<ul>
<li><p>Overestimate or underestimate? Why?</p>
<p>Suppose <img src="https://latex.codecogs.com/png.latex?y%20=%20%5Cbeta%20x%20+%20%5Ctheta%20z%20+%20%5Cvarepsilon"> where <img src="https://latex.codecogs.com/png.latex?z"> is an omitting variable.</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Balign*%7D~%0Az%20&amp;=%20%5Cgamma%20x+%5Ceta%20%5C%5C%5C%5C%0Ay%20&amp;=%20%5Cbeta%20x%20+%5Cxi%20=%20%5Cbeta%20x%20+%20%5Ctheta%5Cgamma%20x%20+%5Ctheta%5Ceta+%5Cepsilon%0A%5Cend%7Balign*%7D%0A"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?%5Cbeta'=%5Cbeta+%5Ctheta%5Cgamma%5Cneq%5Cbeta"> if <img src="https://latex.codecogs.com/png.latex?%5Ctheta%5Cneq0"> or <img src="https://latex.codecogs.com/png.latex?%5Cgamma%5Cneq0">.</p></li>
</ul>
</section>
</section>
<section id="practice-3-difference-in-differences" class="level2">
<h2 class="anchored" data-anchor-id="practice-3-difference-in-differences">Practice 3: Difference-in-differences</h2>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb50" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb50-1">injury <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fread</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Did/injury.csv"</span>)[ky<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb50-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">setnames</span>(injury, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">old=</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'durat'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'ldurat'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'afchnge'</span>),</span>
<span id="cb50-3">         <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">new=</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'duration'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'log_duration'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'after_1980'</span>))</span>
<span id="cb50-4">injury<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>highearn <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> injury<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>highearn<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb50-5"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">print</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Number of Rows:'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Number of Columns:'</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dim</span>(injury)))</span></code></pre></div></div>
<pre><code>## [1] "Number of Rows: 5626"  "Number of Columns: 30"</code></pre>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb52" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb52-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(injury)</span></code></pre></div></div>
<pre><code>##    duration after_1980 highearn male married hosp indust injtype age  prewage    totmed injdes  benefit ky mi log_duration afhigh lprewage     lage  ltotmed head neck upextr trunk lowback lowextr occdis manuf construc highlpre
## 1:        1          1     TRUE    1       0    1      3       1  26 404.9500 1187.5732   1010 246.8375  1  0     0.000000      1 6.003764 3.258096 7.079667    1    0      0     0       0       0      0     0        0 6.003764
## 2:        1          1     TRUE    1       1    0      3       1  31 643.8250  361.0786   1404 246.8375  1  0     0.000000      1 6.467427 3.433987 5.889095    1    0      0     0       0       0      0     0        0 6.467427
## 3:       84          1     TRUE    1       1    1      3       1  37 398.1250 8963.6572   1032 246.8375  1  0     4.430817      1 5.986766 3.610918 9.100934    1    0      0     0       0       0      0     0        0 5.986766
## 4:        4          1     TRUE    1       1    1      3       1  31 527.8000 1099.6483   1940 246.8375  1  0     1.386294      1 6.268717 3.433987 7.002746    1    0      0     0       0       0      0     0        0 6.268717
## 5:        1          1     TRUE    1       1    0      3       1  23 528.9375  372.8019   1940 211.5750  1  0     0.000000      1 6.270870 3.135494 5.921047    1    0      0     0       0       0      0     0        0 6.270870
## 6:        1          1     TRUE    1       1    0      3       1  34 614.2500  211.0199   1425 176.3125  1  0     0.000000      1 6.420402 3.526361 5.351953    1    0      0     0       0       0      0     0        0 6.420402</code></pre>
<blockquote class="blockquote">
<p>Background (Wooldridge’s Intro Econometrics P411): Meyer, Viscusi, and Durbin (1995) (hereafter, MVD) studied the length of time (in weeks) that an injured worker receives workers’ compensation. On July 15, 1980, Kentucky raised the cap on weekly earnings that were covered by workers’ compensation. An increase in the cap has no effect on the benefit for low-income workers, but it makes it less costly for a high-income worker to stay on workers’ compensation. Therefore, the control group is low-income workers, and the treatment group is high-income workers; high-income workers are defined as those who were subject to the pre-policy change cap. Using random samples both before and after the policy change, MVD were able to test whether more generous workers’ compensation causes people to stay out of work longer (everything else fixed). They started with a difference-in-differences analysis, using log(durat) as the dependent variable. Let afchnge be the dummy variable for observations after the policy change and highearn the dummy variable for high earners.</p>
</blockquote>
<section id="change-after-1980" class="level3">
<h3 class="anchored" data-anchor-id="change-after-1980">Change after 1980</h3>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-econ-1/unnamed-chunk-23-1.png" class="img-fluid"></p>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-econ-1/unnamed-chunk-23-2.png" class="img-fluid"></p>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-econ-1/unnamed-chunk-24-1.png" class="img-fluid"></p>
</section>
<section id="regression-2" class="level3">
<h3 class="anchored" data-anchor-id="regression-2">Regression</h3>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Clog(%5Ctext%7Bduration%7D)%20=%20%5Calpha%20+%20%5Cbeta%20%5Ctext%7Bhighearn%7D%20+%0A%5Cgamma%5Ctext%7Bafter%5C_1980%7D%20+%0A%5Cdelta(%5Ctext%7Bhighearn%7D%20%5Ctimes%20%5Ctext%7Bafter%5C_1980%7D)%20+%20%5Cepsilon%0A"></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb54" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb54-1">model_simple <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(log_duration <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> highearn <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> after_1980 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> highearn <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> after_1980,</span>
<span id="cb54-2">                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> injury)</span>
<span id="cb54-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>(model_simple)</span></code></pre></div></div>
<pre><code>## 
## Call:
## lm(formula = log_duration ~ highearn + after_1980 + highearn * 
##     after_1980, data = injury)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -2.9666 -0.8872  0.0042  0.8126  4.0784 
## 
## Coefficients:
##                         Estimate Std. Error t value Pr(&gt;|t|)    
## (Intercept)             1.125615   0.030737  36.621  &lt; 2e-16 ***
## highearnTRUE            0.256479   0.047446   5.406 6.72e-08 ***
## after_1980              0.007657   0.044717   0.171  0.86404    
## highearnTRUE:after_1980 0.190601   0.068509   2.782  0.00542 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1.269 on 5622 degrees of freedom
## Multiple R-squared:  0.02066,    Adjusted R-squared:  0.02014 
## F-statistic: 39.54 on 3 and 5622 DF,  p-value: &lt; 2.2e-16</code></pre>
<p><strong>Add more controls</strong>: <code>male</code>, <code>married</code>, <code>age</code>, <code>hosp</code> (1 = hospitalized), <code>indust</code> (1 = manuf, 2 = construc, 3 = other), <code>injtype</code> (1-8; categories for different types of injury), <code>lprewage</code> (log of wage prior to filing a claim)</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb56" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb56-1">model_full <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(log_duration <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> highearn <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> after_1980 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> highearn <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> after_1980 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> male <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> </span>
<span id="cb56-2">                   married <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> age <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> hosp <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.factor</span>(indust) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.factor</span>(injtype) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> lprewage,</span>
<span id="cb56-3">                 <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> injury)</span>
<span id="cb56-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>(model_full)</span></code></pre></div></div>
<pre><code>## 
## Call:
## lm(formula = log_duration ~ highearn + after_1980 + highearn * 
##     after_1980 + male + married + age + hosp + as.factor(indust) + 
##     as.factor(injtype) + lprewage, data = injury)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -4.0606 -0.7726  0.0931  0.7314  4.3409 
## 
## Coefficients:
##                          Estimate Std. Error t value Pr(&gt;|t|)    
## (Intercept)             -1.528202   0.422212  -3.620 0.000298 ***
## highearnTRUE            -0.151781   0.089116  -1.703 0.088591 .  
## after_1980               0.049540   0.041321   1.199 0.230624    
## male                    -0.084289   0.042315  -1.992 0.046427 *  
## married                  0.056662   0.037305   1.519 0.128845    
## age                      0.006507   0.001338   4.863 1.19e-06 ***
## hosp                     1.130493   0.037006  30.549  &lt; 2e-16 ***
## as.factor(indust)2       0.183864   0.054131   3.397 0.000687 ***
## as.factor(indust)3       0.163485   0.037852   4.319 1.60e-05 ***
## as.factor(injtype)2      0.935468   0.143731   6.508 8.29e-11 ***
## as.factor(injtype)3      0.635466   0.085442   7.437 1.19e-13 ***
## as.factor(injtype)4      0.554550   0.092849   5.973 2.49e-09 ***
## as.factor(injtype)5      0.641201   0.085435   7.505 7.15e-14 ***
## as.factor(injtype)6      0.615041   0.086312   7.126 1.17e-12 ***
## as.factor(injtype)7      0.991336   0.190532   5.203 2.03e-07 ***
## as.factor(injtype)8      0.434082   0.118912   3.650 0.000264 ***
## lprewage                 0.284481   0.080056   3.554 0.000383 ***
## highearnTRUE:after_1980  0.168721   0.063975   2.637 0.008381 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1.15 on 5329 degrees of freedom
##   (279 observations deleted due to missingness)
## Multiple R-squared:  0.1899, Adjusted R-squared:  0.1873 
## F-statistic: 73.46 on 17 and 5329 DF,  p-value: &lt; 2.2e-16</code></pre>
<p><strong>Summary</strong></p>
<pre><code>## 
## =================================================
##                          Simple       Full       
## -------------------------------------------------
## (Intercept)                 1.13 ***    -1.53 ***
##                            (0.03)       (0.42)   
## highearnTRUE                0.26 ***    -0.15    
##                            (0.05)       (0.09)   
## after_1980                  0.01         0.05    
##                            (0.04)       (0.04)   
## highearnTRUE:after_1980     0.19 **      0.17 ** 
##                            (0.07)       (0.06)   
## -------------------------------------------------
## Additional Controls        NO          YES       
## R^2                         0.02         0.19    
## Adj. R^2                    0.02         0.19    
## Num. obs.                5626         5347       
## =================================================
## *** p &lt; 0.001; ** p &lt; 0.01; * p &lt; 0.05</code></pre>


</section>
</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Causal</category>
  <category>Causal-ATE/CATE</category>
  <category>Causal-DAG</category>
  <category>Causal-Matching</category>
  <category>Causal-IPW</category>
  <category>Causal-DID</category>
  <guid>https://yanghaowang.github.io/posts/causal-inference-econ-1/</guid>
  <pubDate>Mon, 07 Feb 2022 07:36:54 GMT</pubDate>
</item>
<item>
  <title>Short Notes on A/B Testing</title>
  <link>https://yanghaowang.github.io/posts/ab-testing-notes/</link>
  <description><![CDATA[ 






<p class="twelve columns" style="text-align: center;">
<img src="https://yanghaowang.github.io/posts/ab-testing-notes/ABTesting.jpg" class="img-fluid">
</p>
<section id="short-notes-on-ab-testing" class="level2">
<h2 class="anchored" data-anchor-id="short-notes-on-ab-testing">Short Notes on A/B Testing</h2>
<section id="motivation" class="level3">
<h3 class="anchored" data-anchor-id="motivation">Motivation</h3>
<ul>
<li>Understand what drives your business and provide insights for business decisions<br>
</li>
<li>Understand causal relationship</li>
</ul>
</section>
<section id="prerequisites" class="level3">
<h3 class="anchored" data-anchor-id="prerequisites">Prerequisites</h3>
<ul>
<li>The control and testing groups can be clearly defined</li>
<li>Metrics of interest can be quantified</li>
<li>Data can be collected in a timely manner</li>
</ul>
</section>
<section id="five-stages-in-practice" class="level3">
<h3 class="anchored" data-anchor-id="five-stages-in-practice">Five Stages in Practice</h3>
<ul>
<li>Define a study question</li>
<li>Make hypotheses (variations) and identify metrics</li>
<li>Identify variables
<ul>
<li>Determine the data to be collected</li>
</ul></li>
<li>Run experiments and collect data
<ul>
<li>Determine a detectable difference (i.e., how small of a difference you would like to detect, for example, 10% increase in your metric of interest)</li>
<li>Calculate the proper sample size using power analysis</li>
<li>Determine what fraction of traffic can be used in the treatment</li>
<li>Conduct a prior A/A test to check unfavorable impacts on business and a simultaneous A/A test to track seasonality and systematic biases/trend if any</li>
</ul></li>
<li>Measure results</li>
</ul>
<p class="twelve columns" style="text-align: center;">
<img src="https://yanghaowang.github.io/posts/ab-testing-notes/ABTestingSteps.png" class="img-fluid">
</p>
</section>
<section id="some-details-in-ab-testing" class="level3">
<h3 class="anchored" data-anchor-id="some-details-in-ab-testing">Some Details in A/B Testing</h3>
<section id="common-web-analytics-metrics" class="level4">
<h4 class="anchored" data-anchor-id="common-web-analytics-metrics">Common Web Analytics Metrics</h4>
<table class="caption-top table">
<colgroup>
<col style="width: 32%">
<col style="width: 32%">
<col style="width: 18%">
<col style="width: 15%">
</colgroup>
<thead>
<tr class="header">
<th>Count</th>
<th>Conversion</th>
<th>Time</th>
<th>Business</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Page View <br>Visits / Return Visits<br>Click <br>Visitor / Unique Visitor <br>(Daily / Monthly) Active Users</td>
<td>Click Thru Rate <br>Click Thru Probability <br>User Click Probability <br>Bounce Rate</td>
<td>Active Time <br>Page View Duration</td>
<td>Revenue <br>Member <br>Order</td>
</tr>
</tbody>
</table>
<p>In addition, we can also consider a composite metric.</p>
</section>
<section id="examples-of-changes-for-testing" class="level4">
<h4 class="anchored" data-anchor-id="examples-of-changes-for-testing">Examples of Changes for Testing</h4>
<ul>
<li>Page Contents
<ul>
<li>Headlines, Sub Headlines, Font Size</li>
<li>Background Image, Background Color</li>
<li>Paragraph Text</li>
<li>Page Layout</li>
</ul></li>
<li>Call-to-Action
<ul>
<li>Button Place, Button Color, Button Size</li>
<li>Text</li>
</ul></li>
</ul>
<p>Notes: <em>Only one thing can be changed in a pair of the control and treatment group.</em></p>
</section>
<section id="experiment-settings" class="level4">
<h4 class="anchored" data-anchor-id="experiment-settings">Experiment Settings</h4>
<ul>
<li><p>Target Audience</p>
<ul>
<li>Country, Region</li>
<li>Demographics</li>
</ul></li>
<li><p>Sample Size</p></li>
<li><p>Experiment Period (Time)</p></li>
<li><p>Percentage of Traffic for A/B Testing</p></li>
<li><p>Split for Control and Treatment</p>
<p>Notes: Users visiting the page at different time or using different devices might see different features in the test. These are users in the mixed group, neither in A or B. To solve this problem, we might need to evenly split users in the control and treatment group. Theoretically, the percentages of the mixed group users in A and B should be similar.</p></li>
<li><p>A/A Test</p>
<ul>
<li><p>Run a small A/A test in a short time prior to the A/B test to check the change in metrics of interest and whether there are any unfavorable impacts on business</p></li>
<li><p>Run an A/A test simultaneously to track the systematic trend during the A/B test period</p></li>
</ul></li>
</ul>
</section>
<section id="power-analysis" class="level4">
<h4 class="anchored" data-anchor-id="power-analysis">Power Analysis</h4>
<ul>
<li><strong>False Positive</strong> (Type I Error): Falsely reject the null hypothesis
<ul>
<li>False positive rate (<img src="https://latex.codecogs.com/png.latex?%5Calpha">, e.g., 5%) is the significant level of a statistic test</li>
</ul></li>
<li><strong>False Negative</strong> (Type II Error): Fail to reject (i.e., we should reject but we did not)
<ul>
<li>False negative rate (<img src="https://latex.codecogs.com/png.latex?%5Cbeta">, e.g., 20%) is used in calculating the power of a test, i.e., <img src="https://latex.codecogs.com/png.latex?1-%5Cbeta"></li>
</ul></li>
</ul>
<p>Discuss the values of <img src="https://latex.codecogs.com/png.latex?%5Calpha"> and <img src="https://latex.codecogs.com/png.latex?%5Cbeta"> with business partners.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Here is a function in R</span></span>
<span id="cb1-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># https://www.rdocumentation.org/packages/stats/versions/3.6.2/topics/power.prop.test</span></span>
<span id="cb1-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># power.prop.test(n = NULL, p1 = NULL, p2 = NULL, </span></span>
<span id="cb1-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#                 power = NULL, sig.level = 0.05,</span></span>
<span id="cb1-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#                 alternative = c("two.sided", "one.sided"),</span></span>
<span id="cb1-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#                 strict = FALSE, tol = .Machine$double.eps^0.25)</span></span>
<span id="cb1-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Examples</span></span>
<span id="cb1-8"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">power.prop.test</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">p1 =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">p2 =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.75</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">power =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.90</span>) <span class="do" style="color: #5E5E5E;
background-color: null;
font-style: italic;">## =&gt;     n = 76.7 in each group</span></span>
<span id="cb1-9"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">power.prop.test</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">p1 =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">p2 =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.501</span>, </span>
<span id="cb1-10">                <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">power =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.90</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sig.level=</span>.<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">001</span>)      <span class="do" style="color: #5E5E5E;
background-color: null;
font-style: italic;">## =&gt;     n = 10451937 in each group</span></span>
<span id="cb1-11"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">power.prop.test</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">p1 =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">p2 =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.75</span>)       <span class="do" style="color: #5E5E5E;
background-color: null;
font-style: italic;">## =&gt; power = 0.740</span></span>
<span id="cb1-12"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">power.prop.test</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">p1 =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">power =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.90</span>)    <span class="do" style="color: #5E5E5E;
background-color: null;
font-style: italic;">## =&gt;    p2 = 0.8026</span></span>
<span id="cb1-13"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">power.prop.test</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">p1 =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">p2 =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.9</span>,</span>
<span id="cb1-14">                <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">power =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.90</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sig.level=</span><span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>)      <span class="do" style="color: #5E5E5E;
background-color: null;
font-style: italic;">## =&gt; sig.l = 0.00131</span></span></code></pre></div></div>
</section>
<section id="result-evaluation" class="level4">
<h4 class="anchored" data-anchor-id="result-evaluation">Result Evaluation</h4>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Group</th>
<th>Control - A</th>
<th>Variation - B</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Unique Visitor</td>
<td>500</td>
<td>500</td>
</tr>
<tr class="even">
<td>Unique Click</td>
<td>50</td>
<td>60</td>
</tr>
<tr class="odd">
<td>Conversion Rate</td>
<td>10%</td>
<td>12%</td>
</tr>
</tbody>
</table>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?H_0:%5Cspace%20d=0"></li>
<li><img src="https://latex.codecogs.com/png.latex?d%20%5Csim%20N(0,SE)">
<ul>
<li><img src="https://latex.codecogs.com/png.latex?p_%7B%5Ctext%7Bpool%7D%7D=%5Cfrac%7B50+60%7D%7B500+500%7D=0.11"></li>
<li><img src="https://latex.codecogs.com/png.latex?SE=%5Csqrt%7Bp_%7B%5Ctext%7Bpool%7D%7D%5Ctimes(1-p_%7B%5Ctext%7Bpool%7D%7D)%5Ctimes(%5Cfrac%7B1%7D%7BN_A%7D+%5Cfrac%7B1%7D%7BN_B%7D)%7D=0.019789"></li>
</ul></li>
<li>Calculate 95% confidence interval (<img src="https://latex.codecogs.com/png.latex?%5Calpha=5%5C%25">)
<ul>
<li><img src="https://latex.codecogs.com/png.latex?%5Cpm%20z_%7B%5Calpha/2%7D%5Ctimes%20SE%5Cimplies%20(-1.96%5Ctimes%20SE,%201.96%5Ctimes%20SE)=(-0.0388,%200.0388)"></li>
<li><img src="https://latex.codecogs.com/png.latex?d%20=%2012%5C%25%20-%2010%5C%25%20=0.02%20%3C%200.0388"></li>
<li>Cannot reject <img src="https://latex.codecogs.com/png.latex?H_0"></li>
</ul></li>
<li>Suppose <img src="https://latex.codecogs.com/png.latex?N_A"> and <img src="https://latex.codecogs.com/png.latex?N_B"> become 10 times larger
<ul>
<li><img src="https://latex.codecogs.com/png.latex?SE=0.00003916"></li>
<li><img src="https://latex.codecogs.com/png.latex?%5Cpm%20z_%7B%5Calpha/2%7D%5Ctimes%20SE%20=%20%5Cpm%200.0000767536"></li>
<li><img src="https://latex.codecogs.com/png.latex?d=0.02%3E0.0000767536"></li>
<li>Reject <img src="https://latex.codecogs.com/png.latex?H_0"></li>
</ul></li>
</ul>
</section>
</section>
<section id="some-challenges-in-ab-testing" class="level3">
<h3 class="anchored" data-anchor-id="some-challenges-in-ab-testing">Some Challenges in A/B Testing</h3>
<section id="tradeoff-between-alpha-and-beta" class="level4">
<h4 class="anchored" data-anchor-id="tradeoff-between-alpha-and-beta">Tradeoff between <img src="https://latex.codecogs.com/png.latex?%5Calpha"> and <img src="https://latex.codecogs.com/png.latex?%5Cbeta"></h4>
<ul>
<li><p>By definition, <img src="https://latex.codecogs.com/png.latex?%5Calpha"> is the false positive rate, representing the chance that we falsely reject <img src="https://latex.codecogs.com/png.latex?H_0">. In contrast, <img src="https://latex.codecogs.com/png.latex?%5Cbeta"> is the false negative rate, representing the chance that we should reject but didn’t.</p></li>
<li><p>Since resources and time are limited, we need put the effect on the project that improves the business most significantly and has the largest favorable business impact.</p></li>
<li><p>As a result, we might emphasize <img src="https://latex.codecogs.com/png.latex?%5Calpha"> at expense of <img src="https://latex.codecogs.com/png.latex?%5Cbeta">. Also, remember to reach an agreement with business before the test.</p></li>
</ul>
</section>
<section id="insignificant-treatment-effect" class="level4">
<h4 class="anchored" data-anchor-id="insignificant-treatment-effect">Insignificant Treatment Effect</h4>
<ul>
<li>It is worth noting that the difference between control and treatment is <em>insignificant in statistics</em>. The testing feature can be helpful in the long run.</li>
<li>Generate a line plot to visualize the difference and check if one is above the other in most of the time, though the difference could be statistically insignificant. Such a line plot can also provide some insights.</li>
</ul>
</section>
<section id="multi-armed-bandit-approach" class="level4">
<h4 class="anchored" data-anchor-id="multi-armed-bandit-approach">Multi-armed Bandit Approach</h4>
<p>We want to achieve two goals at a time: (1) find the best variant in a longer time of experiment and (2) maximize the revenue during the experiment period as well.</p>
<ul>
<li>Solution: Adjust fraction of (new) users in treatment/control according to which group seems to be doing better.</li>
</ul>


</section>
</section>
</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>A/B Testing</category>
  <guid>https://yanghaowang.github.io/posts/ab-testing-notes/</guid>
  <pubDate>Fri, 17 Sep 2021 00:57:33 GMT</pubDate>
</item>
<item>
  <title>How to Use Class Objects in Python</title>
  <link>https://yanghaowang.github.io/posts/python-class-objects/</link>
  <description><![CDATA[ 






<p>I am used to statistical programming and use self-defined functions a lot in R. In my research work, a self-defined function works well in most cases since the scalability and flexibility of codes are less of concern. However, as using more Python and reading more source codes of Python packages, I find <code>class</code> is an important object and deserves a brief study on it.</p>
<p>A class is a prototype for an object, from which new instances can be created. An instance is a copy of the class with actual values.</p>
<section id="class-object" class="level2">
<h2 class="anchored" data-anchor-id="class-object">Class Object</h2>
<p>A given class object consists of two components:</p>
<ul>
<li>State: Attributes/properties of an object</li>
<li>Behavior: Methods of an object</li>
</ul>
<p>All the instances share the attributes and the methods of the class. But the values of attributes are unique for each instance. Let’s see an example as follows.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Define a python class named 'makecake'</span></span>
<span id="cb1-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> makecake:</span>
<span id="cb1-3">    </span>
<span id="cb1-4">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Define class variables</span></span>
<span id="cb1-5">    cook <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Sharon'</span></span>
<span id="cb1-6">    price_lb <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># unit price; dollars per lb</span></span>
<span id="cb1-7">    </span>
<span id="cb1-8">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Initialize</span></span>
<span id="cb1-9">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, weight):</span>
<span id="cb1-10">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Define instance variables</span></span>
<span id="cb1-11">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.weight <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> weight</span>
<span id="cb1-12">       </span>
<span id="cb1-13">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Define a method for an instance</span></span>
<span id="cb1-14">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> price(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb1-15">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.weight<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.price_lb</span></code></pre></div></div>
<blockquote class="blockquote">
<p><code>makecake</code> is the class name.</p>
<p><code>cook</code> and <code>price_lb</code> are the class attributes, representing the cook and the unit price of a cake.</p>
<p><code>price()</code> is the class method used to calculate the cake price.</p>
<p><code>__init__</code> method is a preserved method for a class object, used to initializing its state. The <code>__init__</code> method is executed at the time the class is instantiated (i.e., the creation of an instance).</p>
<p><code>self</code> is a must-have parameter in each class method, though it might take no arguments. When we call a method of an object as <code>myobject.method(arg1, arg2)</code>, it is equivalent to the command that <code>MyClass.method(myobject, arg1, arg2)</code>.</p>
</blockquote>
<p>Also, note that <code>weight</code> is a variable <em>unique to each instance</em>, while <code>cook</code>, <code>price_lb</code>, <code>price()</code> are <em>class variables</em> shared by all instances of the class.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1">cake <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> makecake(weight<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb2-2"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(cake.cook)</span>
<span id="cb2-3"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(cake.price_lb)</span>
<span id="cb2-4">cake.price()</span></code></pre></div></div>
<pre><code>Sharon
5
10</code></pre>
</section>
<section id="inheritance" class="level2">
<h2 class="anchored" data-anchor-id="inheritance">Inheritance</h2>
<p>Inheritance allows us to define a class that inherits all the methods and properties from another class. For example, inherited from <code>makecake</code>, I declare a new class <code>ordercake</code> as follows.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Define a python class based on 'makecake'</span></span>
<span id="cb4-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> ordercake(makecake):</span>
<span id="cb4-3">    </span>
<span id="cb4-4">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Initialize</span></span>
<span id="cb4-5">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, weight, tax_rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>):</span>
<span id="cb4-6">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Define instance variables</span></span>
<span id="cb4-7">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.weight <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> weight</span>
<span id="cb4-8">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.tax_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tax_rate <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> tax_rate <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.06</span></span>
<span id="cb4-9">    </span>
<span id="cb4-10">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> checkout(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, tip<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>):</span>
<span id="cb4-11">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> tip <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb4-12">            tip <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb4-13">        </span>
<span id="cb4-14">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># self.price() is inherited from 'makecake'</span></span>
<span id="cb4-15">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Receipt'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">--------------------'</span></span>
<span id="cb4-16">              <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Cake Price:'</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">round</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.price(), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>),</span>
<span id="cb4-17">              <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Tax:'</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">round</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.price()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.tax_rate, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>),</span>
<span id="cb4-18">              <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Tips:'</span>, tip, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">--------------------'</span>,</span>
<span id="cb4-19">              <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Total:'</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">round</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.price()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.tax_rate)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>tip, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span></code></pre></div></div>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1">myorder0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ordercake(weight<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb5-2">myorder0.checkout()</span></code></pre></div></div>
<pre><code>Receipt 
--------------------
Cake Price: 10 
Tax: 0.6 
Tips: 0 
-------------------- 
Total: 10.6</code></pre>
<p>In addtion to the inherited attributes, I add another attribute <code>tax_rate</code> in the <code>ordercake</code> class to calculate the cake price after tax such that <img src="https://latex.codecogs.com/png.latex?%0A%5Ctext%7BCake%20Price%20after%20Tax%7D=%5Ctext%7BCake%20Price%20before%20Tax%7D%5Ctimes(1+%5Ctext%7BTax%20Rate%7D).%0A"></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1">myorder1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ordercake(weight<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, tax_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.08</span>)</span>
<span id="cb7-2">myorder1.checkout()</span></code></pre></div></div>
<pre><code>Receipt 
--------------------
Cake Price: 10 
Tax: 0.8 
Tips: 0 
-------------------- 
Total: 10.8</code></pre>
<pre class="pytho"><code>myorder1.checkout(tip=2)</code></pre>
<pre><code>Receipt 
--------------------
Cake Price: 10 
Tax: 0.8 
Tips: 2 
-------------------- 
Total: 12.8</code></pre>
</section>
<section id="use-self-defined-function-in-class" class="level2">
<h2 class="anchored" data-anchor-id="use-self-defined-function-in-class">Use Self-defined Function in Class</h2>
<p>To enhance the <code>ordercake</code> class, I add an additional function to determine the delivery fee as follows.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Define a free-delivery function</span></span>
<span id="cb11-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> free_delivery(order_price):</span>
<span id="cb11-3">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Define the delivery fee</span></span>
<span id="cb11-4">    delivery_fee <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span></span>
<span id="cb11-5">    </span>
<span id="cb11-6">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Waive delivery fee if order price &gt;= 15 dollars</span></span>
<span id="cb11-7">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> order_price <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>:</span>
<span id="cb11-8">        delivery_fee <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb11-9">    </span>
<span id="cb11-10">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> delivery_fee</span>
<span id="cb11-11"></span>
<span id="cb11-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Define a python class based on 'makecake'</span></span>
<span id="cb11-13"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> ordercake_delivery(makecake):</span>
<span id="cb11-14">        </span>
<span id="cb11-15">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, weight, delivery, tax_rate<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>):</span>
<span id="cb11-16">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Define instance variables</span></span>
<span id="cb11-17">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.weight <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> weight</span>
<span id="cb11-18">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.delivery_fcn <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> delivery</span>
<span id="cb11-19">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.tax_rate <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tax_rate <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> tax_rate <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.06</span></span>
<span id="cb11-20">        </span>
<span id="cb11-21">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> checkout(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, tip<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>):</span>
<span id="cb11-22">        d_fee <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.delivery_fcn(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.price())</span>
<span id="cb11-23">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> tip <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb11-24">            tip <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb11-25">            </span>
<span id="cb11-26">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Receipt'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">--------------------'</span></span>
<span id="cb11-27">              <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Cake Price:'</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">round</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.price(), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>),</span>
<span id="cb11-28">              <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Tax:'</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">round</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.price()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.tax_rate, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>),</span>
<span id="cb11-29">              <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Tips:'</span>, tip,</span>
<span id="cb11-30">              <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Delivery:'</span>, d_fee, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">--------------------'</span>,</span>
<span id="cb11-31">              <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">Total:'</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">round</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.price()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.tax_rate)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>tip<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span>d_fee, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span></code></pre></div></div>
<p>A delivery fee of 5 dollars is added to the receipt if the cake price is less than 15 dollars.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1">myorder2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ordercake_delivery(weight<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, delivery<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>free_delivery)</span>
<span id="cb12-2">myorder2.checkout()</span></code></pre></div></div>
<pre><code>Receipt 
--------------------
Cake Price: 10 
Tax: 0.6 
Tips: 0 
Delivery: 5 
-------------------- 
Total: 15.6</code></pre>
<p>In contrast, the delivery fee is waived if the cake price is 15 dollars or above.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1">myorder3 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ordercake_delivery(weight<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, delivery<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>free_delivery)</span>
<span id="cb14-2">myorder3.checkout(tip<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<pre><code>Receipt 
--------------------
Cake Price: 15 
Tax: 0.9 
Tips: 2 
Delivery: 0 
-------------------- 
Total: 17.9</code></pre>
</section>
<section id="reference" class="level2">
<h2 class="anchored" data-anchor-id="reference">Reference</h2>
<p>Python Classes and Objects at GeeksforGeeks: https://www.geeksforgeeks.org/python-classes-and-objects/</p>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Python</category>
  <guid>https://yanghaowang.github.io/posts/python-class-objects/</guid>
  <pubDate>Wed, 11 Aug 2021 05:50:09 GMT</pubDate>
</item>
<item>
  <title>Path to Virtual Drive</title>
  <link>https://yanghaowang.github.io/posts/virtual-drive-path/</link>
  <description><![CDATA[ 






<p class="twelve columns" style="text-align: center;">
<img src="https://yanghaowang.github.io/posts/virtual-drive-path/SyncingGoogleDrive.png" class="img-fluid">
</p>
<p>This July, Google released a new Google Drive desktop app to replace old versions. The biggest change is that I cannot find a local path for files that are selected to be synced to the corresponding files in Google Drive.</p>
<section id="problem" class="level2">
<h2 class="anchored" data-anchor-id="problem">Problem</h2>
<p>It bothered me since I mapped a virtual drive <code>W:</code> to the local Google Drive folder using a <code>.bat</code> file with a Windows command <a href="https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/subst"><code>subst</code></a> executed when I log into Windows. I learned this trick from my professor at UTK. It allowed me to keep a consistent working directory in my coding scripts. At the beginning of a script, I usually define a working directory at <code>W:</code> which is synced to my Google Drive. Using this trick, I no longer need to change the existing directory when switching my working computer from the desktop in my office to the laptop at home.</p>
<p>Now, the new Google Drive desktop app does not maintain a local path. Instead, it creates a drive, named “Google Drive,” after it starts as I am logging into Windows. The computer executes the selected software in the Windows Startup list. However, the new Google Drive app takes a little longer to fully start than my <code>.bat</code>. Therefore, when the <code>.bat</code> starts, it cannot find the corresponding path to be mapped to <code>W:</code>.</p>
</section>
<section id="solution" class="level2">
<h2 class="anchored" data-anchor-id="solution">Solution</h2>
<p>I turn off “Google Drive” in the Windows Startup list, while use the <code>.bat</code> file to start it before executing the <code>subst</code> command.</p>
<p>Here is an example of my <code>.bat</code> file, say <code>vdrive.bat</code>.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode powershell code-with-copy"><code class="sourceCode powershell"><span id="cb1-1">@echo off</span>
<span id="cb1-2">subst M<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"C:\Users\&lt;username&gt;\OneDrive - azureford"</span></span>
<span id="cb1-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">start</span> C<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>\<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Program Files"</span>\Google\<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Drive File Stream"</span>\<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">51.0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16.0</span>\GoogleDriveFS<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exe</span></span>
<span id="cb1-4">timeout <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>t <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>nobreak <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> nul</span>
<span id="cb1-5">subst W<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"G:\My Drive"</span></span></code></pre></div></div>
<blockquote class="blockquote">
<p>Notes: Please replace <code>&lt;username&gt;</code> with your username. If interested, feel free to check the references for windows commands, <a href="https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/echo"><code>echo</code></a>, <a href="https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/start"><code>start</code></a>, and <a href="https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/timeout"><code>timeout</code></a>.</p>
</blockquote>
<p><code>vdrive.bat</code> will be started as I log into Windows if it is added to Windows Registry as a string value in <code>[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run]</code>. I need define a value name and the value data for this string value, where the value name is a string displayed in the Windows Startup list and the value data is a path with double quotation marks at both ends, e.g., <code>"C:\vdrive.bat"</code>.</p>
<p>Every time, when <code>vdrive.bat</code> starts, a Command Prompt window appears. I don’t want to see that as I log into Windows. So I create a shortcut for <code>vdrive.bat</code>, that is, <code>vdrive.bat.lnk</code>. Right click the shortcut file, choose “Minimized” in Run, and save the change. Then I update the value data to <code>"C:\vdrive.bat.lnk"</code> in Windows Registry. Awesome, it works perfectly!</p>
<p>Don’t want to work in Windows Registry for the Startup list. No problem. You can put the shortcut in the following directory:</p>
<blockquote class="blockquote">
<p>Startup folder for user: <code>C:\Users\&lt;username&gt;\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup</code></p>
<p>Startup folder for all users: <code>C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup</code></p>
</blockquote>
<section id="navigating-in-command-prompt" class="level3">
<h3 class="anchored" data-anchor-id="navigating-in-command-prompt">Navigating in Command Prompt</h3>
<p>In Command Prompt, the default <a href="https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/cd"><code>cd</code></a> command allows us to change the working directory within the same drive. When changing to a directory in another drive,</p>
<ol type="1">
<li>we need switch to the target drive first by typing the letter of the drive and then direct us to the target directory using <code>cd</code>, or</li>
<li>we can add a parameter in the <code>cd</code> command, i.e., <code>cd /d "&lt;path in another drive&gt;"</code>.</li>
</ol>
<p class="twelve columns" style="text-align: center;">
<img src="https://yanghaowang.github.io/posts/virtual-drive-path/cd_command.png" class="img-fluid">
</p>


</section>
</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>CMD</category>
  <category>Work Efficiency</category>
  <guid>https://yanghaowang.github.io/posts/virtual-drive-path/</guid>
  <pubDate>Tue, 20 Jul 2021 18:54:41 GMT</pubDate>
</item>
<item>
  <title>GitHub Authentication and Basic Functionalities</title>
  <link>https://yanghaowang.github.io/posts/github-basics/</link>
  <description><![CDATA[ 






<p>Recently, I share with colleagues my knowledge of Git/GitHub. I gave a presentation in a team meeting, which covers the authentication and the basic functionalities of GitHub.</p>
<p class="twelve columns" style="text-align: center;">
<img src="https://yanghaowang.github.io/posts/github-basics/Git_GitHub.png" class="img-fluid">
</p>
<p>The authentication setting of GitHub in Git is not as easy as that in the GitHub Desktop App. Most beginners are overwhelmed by large numbers of relevant posts. Therefore, I list the <em>only necessary official</em> references that you can follow step by step to set up the authentication. Moreover, from my perspectives, I list the basic functionalities of GitHub as well as the corresponding daily Git commands. Lastly, I share some rules of thumb for collaboration in GitHub.</p>
<section id="authentication" class="level2">
<h2 class="anchored" data-anchor-id="authentication">Authentication</h2>
<p><em>You must authenticate before you can access certain resources on GitHub</em>. When you authenticate to GitHub, you supply or confirm credentials that are unique to you to prove that you are exactly who you declare to be. The most two popular ways to authenticate to GitHub are</p>
<ol type="1">
<li>A Combination of Username and Personal Access Token, and</li>
<li>The SSH Protocol</li>
</ol>
<section id="username-and-token" class="level3">
<h3 class="anchored" data-anchor-id="username-and-token">Username and Token</h3>
<ol type="1">
<li><p>Creating a personal access token: https://docs.github.com/en/github/authenticating-to-github/keeping-your-account-and-data-secure/creating-a-personal-access-token#creating-a-token</p></li>
<li><p>Using a token on the command line: https://docs.github.com/en/github/authenticating-to-github/keeping-your-account-and-data-secure/creating-a-personal-access-token#using-a-token-on-the-command-line</p></li>
</ol>
</section>
<section id="ssh" class="level3">
<h3 class="anchored" data-anchor-id="ssh">SSH</h3>
<ol type="1">
<li>Checking for existing SSH keys: https://docs.github.com/en/github/authenticating-to-github/connecting-to-github-with-ssh/checking-for-existing-ssh-keys</li>
<li>Generating a new SSH key and adding it to the ssh-agent: https://docs.github.com/en/github/authenticating-to-github/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent</li>
<li>Adding a new SSH key to your GitHub account: https://docs.github.com/en/github/authenticating-to-github/connecting-to-github-with-ssh/adding-a-new-ssh-key-to-your-github-account</li>
</ol>
<p>With SSH keys, you can connect to GitHub without supplying your username and personal access token at each visit.</p>
<p class="twelve columns" style="text-align: center;">
<img src="https://yanghaowang.github.io/posts/github-basics/GitHubAuthentication.png" class="img-fluid">
</p>
</section>
</section>
<section id="basic-functionalities" class="level2">
<h2 class="anchored" data-anchor-id="basic-functionalities">Basic Functionalities</h2>
<section id="adding-an-existing-project-to-github" class="level3">
<h3 class="anchored" data-anchor-id="adding-an-existing-project-to-github">Adding an existing project to GitHub</h3>
<p>https://docs.github.com/en/github/importing-your-projects-to-github/importing-source-code-to-github/adding-an-existing-project-to-github-using-the-command-line</p>
</section>
<section id="cloning-a-repository" class="level3">
<h3 class="anchored" data-anchor-id="cloning-a-repository">Cloning a repository</h3>
<p>https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/cloning-a-repository-from-github/cloning-a-repository</p>
</section>
<section id="branch-checkoutbranch" class="level3">
<h3 class="anchored" data-anchor-id="branch-checkoutbranch">Branch: Checkout/Branch</h3>
<ol type="1">
<li>Create a new branch using <code>git branch &lt;branch_name&gt;</code>.</li>
<li>Switch to the new branch using <code>git checkout &lt;branch_name&gt;</code>.</li>
</ol>
<p>Execute two command lines in one: <code>git checkout -b &lt;branch_name&gt;</code></p>
</section>
<section id="adding-a-file-to-a-repository" class="level3">
<h3 class="anchored" data-anchor-id="adding-a-file-to-a-repository">Adding a file to a repository</h3>
<p>https://docs.github.com/en/github/managing-files-in-a-repository/managing-files-using-the-command-line/adding-a-file-to-a-repository-using-the-command-line</p>
</section>
<section id="remove-files-from-the-working-directory" class="level3">
<h3 class="anchored" data-anchor-id="remove-files-from-the-working-directory">Remove files from the working directory</h3>
<ol type="1">
<li>Remove files (e.g.&nbsp;trash.txt) from local directory manually.</li>
<li><code>git rm trash.txt</code> in Git Bash.</li>
<li>Commit the change using <code>git commit -m "Remove trash.txt"</code>.</li>
</ol>
</section>
<section id="pull-and-push" class="level3">
<h3 class="anchored" data-anchor-id="pull-and-push">Pull and Push</h3>
<ol type="1">
<li>Check the target remote repository on GitHub using <code>git remote -v</code>.</li>
<li>Pull the latest changes from GitHub with <code>git pull</code>.</li>
<li>Push your work to GitHub with <code>git push origin &lt;branch_name&gt;"</code> where <code>origin</code> is referred to as the target remote repository.</li>
</ol>
</section>
<section id="merge" class="level3">
<h3 class="anchored" data-anchor-id="merge">Merge</h3>
<p>Merge code changes in two different branches (target branch and to be merged branch)</p>
<ol type="1">
<li>Checkout the target branch using <code>git checkout &lt;target_bread&gt;</code>.</li>
<li>Merge the changes from to-be-merged-branch into the target branch using <code>git merge &lt;to_be_merged_branch&gt;</code>.</li>
</ol>
</section>
<section id="revert-and-reset" class="level3">
<h3 class="anchored" data-anchor-id="revert-and-reset">Revert and Reset</h3>
<p><code>git revert &lt;commit_ID&gt;</code> will undo the changes in a particular commit.</p>
<ul>
<li><p><code>git reset</code></p></li>
<li><p><code>git commit --amend</code></p></li>
</ul>
</section>
</section>
<section id="best-practices-for-collaboration" class="level2">
<h2 class="anchored" data-anchor-id="best-practices-for-collaboration">Best Practices for Collaboration</h2>
<ol type="1">
<li>Always synchronize your branches before starting any work on your own.</li>
<li>Make changes that are self-contained.</li>
<li>Avoid having very large changes that modify a lot of different things. (Try to make changes as small as possible as long as they’re self-contained.)</li>
<li>When working on a big change, it makes sense to have a separate feature branch.</li>
<li>Regularly merge changes made on the master branch back onto the feature branch.</li>
<li>Have the latest version of the project in the master branch, and the stable version of the project on a separate branch.</li>
<li>You shouldn’t rebase changes that have been pushed to remote repos.</li>
<li>Write commit messages.</li>
<li>Only edit the same branch when necessary after submitting a pull request.</li>
</ol>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Git</category>
  <category>Github</category>
  <category>Work Efficiency</category>
  <guid>https://yanghaowang.github.io/posts/github-basics/</guid>
  <pubDate>Tue, 15 Jun 2021 19:06:00 GMT</pubDate>
</item>
<item>
  <title>Brief Introduction of Essential Methods in Causal Inference</title>
  <link>https://yanghaowang.github.io/posts/causal-inference-intro/</link>
  <description><![CDATA[ 






<p>Running an AB test becomes a generic solution when we are interested in the causal impacts of a new feature on the product sales or performance. What if we cannot set up the environment of an experiment because of market regulation?</p>
<p>In this post, we turn back to some essential methods in causal inference. These methods are briefly covered by the Coursera Project, titled “<a href="https://www.coursera.org/projects/essential-causal-inference-for-data-science">Essential Causal Inference Techniques for Data Science</a>.”</p>
<section id="idea-behind-causal-inference" class="level2">
<h2 class="anchored" data-anchor-id="idea-behind-causal-inference">Idea behind Causal Inference</h2>
<p>Try to control for all possible confounders and <strong>look for “natural sources” of variation that can split our data into quasi random groups</strong> and mimic the randomization we would get from an AB test.</p>
<p>In other words, removing the effects of all the potential confounders, we believe that testing groups are randomly split and comparable.</p>
</section>
<section id="essential-methods" class="level2">
<h2 class="anchored" data-anchor-id="essential-methods">Essential Methods</h2>
<section id="controlled-regression" class="level3">
<h3 class="anchored" data-anchor-id="controlled-regression">Controlled Regression</h3>
<ul>
<li><p>We have Y =&gt; usage as measured by completing the 2nd week of a course</p></li>
<li><p>and X =&gt; First Week NPS (net promoter score) which is a satisfaction rating on a 1-10 scale</p></li>
<li><p>Univariate regression of Y (usage) on X (product quality)</p></li>
<li><p>Multiple regression of Y (usage) on X (product quality) and a set of controls</p></li>
</ul>
<p>If</p>
<ol type="1">
<li><p>the R squared in the multiple regression increases “a lot” from that in the univariate regression</p></li>
<li><p>coefficient on X is similar in the two models</p></li>
</ol>
<p>then by the theory of controlled regression, we can use it as the causal impact.</p>
<blockquote class="blockquote">
<p>Sources of Error</p>
<ul>
<li><p>Omitted Variable Bias</p>
<p>Look at the R squared in the multiple regression with controls and how large it is (if R<sup>2</sup> is not close to 100% we know there are a lot of omitted variables in our regression)</p></li>
<li><p>Included Variable Bias</p>
<p>This is the opposite of omitted variable bias and involves the inclusion of too many controls. No direct way to identify this problem but generally can leave out controls that are not determined at time observe X. In the ML context, it is the information leakage (e.g., target encoding), that is, using future to predict the past.</p></li>
</ul>
</blockquote>
<p>Controlled regression can be a bit of art form and a bit of random. People nowadays prefer the other causal inference techniques that are considered to be more rigorous and reliable.</p>
</section>
<section id="regression-discontinuity" class="level3">
<h3 class="anchored" data-anchor-id="regression-discontinuity">Regression Discontinuity</h3>
<p>Focus on cut-off point that can be thought of as local randomized experiment.</p>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-intro/RD.png" class="img-fluid"></p>
<blockquote class="blockquote">
<p>Arbitrarily assigned cutoff point randomly splits the sample into two comparable groups around the cutoff point.</p>
</blockquote>
<ul>
<li><p>Y: Revenue or course enrollment</p></li>
<li><p>X: Advertisement (advertised, e.g., via email, if the percentage of subtitled materials in a course is greater than 80%)</p></li>
<li><p>Assumption</p>
<ol type="1">
<li><p>Courses below and above the 80% subtitle threshold are similar to one another, so the discontinuity point effectively randomizes the sample.</p>
<blockquote class="blockquote">
<p>Check:</p>
<ol type="1">
<li>Sample size similar below and above cutoff (i.e., roughly balanced)</li>
<li>Sample below and above cutoff are similar on observable/confounders</li>
</ol>
</blockquote></li>
<li><p>Advertising available or not is assumed to be the only differentiator between courses at the 70% subtitle value and the 90% subtitle value.</p>
<blockquote class="blockquote">
<p>Check:</p>
<p>Conduct placebo tests, that is, run regression discontinuity at points other than the cutoff and check for no effect (e.g., run regression discontinuity at 20%, 30%, and 40% and we shouldn’t find any significant difference at these levels)</p>
</blockquote></li>
</ol></li>
</ul>
<p>Using regression discontinuity design (RDD), we estimate a linear regression with a term of the X variable with the discontinuity, an indicator for the discontinuity (which is a function of the X variable being above or below the cutoff point), and the interaction of the X variable and the discontinuity indicator. <img src="https://latex.codecogs.com/png.latex?%0Ay=%5Cbeta_0+%5Cbeta_1%20%5Ccdot%20x+%5Cbeta_2%20%5Ccdot%20I(x%5Cge%20c)+%5Cbeta_3%5Ccdot%20x%20%5Ccdot%20I(x%5Cge%20c),%0A"> where <img src="https://latex.codecogs.com/png.latex?x"> is the variable with the discontinuity, <img src="https://latex.codecogs.com/png.latex?I(%5Ccdot)"> is an indicator function, and <img src="https://latex.codecogs.com/png.latex?c"> is the randomly assigned cutoff point.</p>
<blockquote class="blockquote">
<p>Note this regression fits two linear models (with different coefficients) below and above the cutoff point. When <img src="https://latex.codecogs.com/png.latex?x%3Cc">, the intercept and the coefficient of the X variable are <img src="https://latex.codecogs.com/png.latex?%5Cbeta_0"> and <img src="https://latex.codecogs.com/png.latex?%5Cbeta_1">. In contrast, when <img src="https://latex.codecogs.com/png.latex?x%5Cge%20c">, the intercept and the coefficient become <img src="https://latex.codecogs.com/png.latex?%5Cbeta_0+%5Cbeta_2"> and <img src="https://latex.codecogs.com/png.latex?%5Cbeta_1+%5Cbeta_3">.</p>
<p>This change in the model structure is analog to the formulation of the Chow test for examining the structural break.</p>
</blockquote>
<p>Comparing pre and post the discontinuity, we obtain the causal effect given by <img src="https://latex.codecogs.com/png.latex?%0A%5Cbeta_2%20+%20%5Cbeta_3%5Ctimes%20c.%0A"></p>
</section>
<section id="difference-in-difference" class="level3">
<h3 class="anchored" data-anchor-id="difference-in-difference">Difference-in-Difference</h3>
<p><img src="https://yanghaowang.github.io/posts/causal-inference-intro/DID.png" class="img-fluid"></p>
<ul>
<li><p>Y: Revenue</p></li>
<li><p>X: Price change</p></li>
<li><p>Assumption: Parallel Trends</p>
<p>Check revenue in control country with no price change was similar and highly correlated with revenue in treatment country with price change (ensure control can serve as counterfactual)</p>
<ol type="1">
<li>Graph control and treatment groups in the pre period and see if highly correlated</li>
<li>Build a regression model to check whether trends are identical (hypotheses testing if there is no difference in slopes between two groups)</li>
</ol></li>
<li><p>Extension: <strong>Synthetic Control</strong></p>
<ul>
<li>Problem with regular DID: Picking a single control group that satisfies parallel trends can be arbitrary</li>
<li>Synthetic control creates a synthetic control group that is a weighted average of many control groups
<ol type="1">
<li>Choose weights to minimize tracking error with treatment group pre intervention (parallel trends)</li>
<li>Causal estimate is difference post intervention between treatment and “synthetic control”</li>
</ol></li>
<li>R packages: <a href="https://cran.r-project.org/web/packages/Synth/index.html"><code>Synth</code></a>; <a href="https://cran.r-project.org/web/packages/CausalImpact/"><code>CausalImpact</code></a> (Bayesian Version)</li>
</ul></li>
</ul>
</section>
<section id="instrumental-variables" class="level3">
<h3 class="anchored" data-anchor-id="instrumental-variables">Instrumental Variables</h3>
<ul>
<li><p>Assumptions</p>
<ol type="1">
<li><p>Strong First Stage: Instruments are strong predictors for the X variable</p>
<p>Hypothesis tests for weak instruments</p></li>
<li><p>Exclusion Restriction: Instruments have an impact on the Y variable only through their impact on the X variable</p>
<p>There is no test for this assumption. We need to use logic to strengthen the validity of this assumption. In a <strong>randomized encouragement trial</strong> (i.e., a RCT used for product promotion campaign; think of email notification) where we create the instrument as a randomly assigned nudge that prompts the X variable, we can ensure exclusion restriction through random assignment.</p></li>
</ol></li>
</ul>
</section>
<section id="machine-learning-ml-causal-inference" class="level3">
<h3 class="anchored" data-anchor-id="machine-learning-ml-causal-inference">Machine Learning (ML) + Causal Inference</h3>
<ul>
<li><p>Weakness of classic causal approaches</p>
<ul>
<li>Fail with many covariates</li>
<li>Model selection unprincipled</li>
<li>Linear relationships and no interactions</li>
</ul></li>
<li><p>Benefits of ML</p>
<ul>
<li>Handle high dimensionality</li>
<li>Principled ways to choose model</li>
<li>Nonlinear model using higher order features</li>
</ul></li>
<li><p>ML form controlled regression</p>
<ul>
<li><p>Use ML models to control for many potential confounders and/or nonlinear effects.</p>
<blockquote class="blockquote">
<p>Standard controlled regression steps</p>
<ul>
<li>Regress Y on X and a set of controls C to identify coefficient of interest on X</li>
<li>Be wary of omitted and included variable biases</li>
</ul>
</blockquote></li>
<li><p>There are two types of ML form controlled regressions:</p>
<ul>
<li>Double Selection (LASSO)</li>
<li>Double Debiased (Generic ML models)</li>
</ul>
<blockquote class="blockquote">
<p>Double Selection on AB test data:</p>
<ul>
<li>Reduce the noises and increase statistical power (give smaller confidence intervals in a shorter experiment period)</li>
<li>Good for small samples and small effect sizes (i.e., small expected difference between A and B groups)</li>
</ul>
</blockquote></li>
<li><p>Steps</p>
<ul>
<li><p>Define outcome Y, treatment indicator X, and high dimensional set of controls C</p></li>
<li><p>Split data into two sets: Training and Testing (this can be generalized to k-folds)</p></li>
<li><p><strong>Fit</strong> two Lassos of X~C and Y~C <strong>on the training</strong> data set</p>
<blockquote class="blockquote">
<p>Use <a href="https://stats.stackexchange.com/questions/138569/why-is-lambda-within-one-standard-error-from-the-minimum-is-a-recommended-valu">the one standard error rule</a> to choose the optimal <img src="https://latex.codecogs.com/png.latex?%5Clambda"> (i.e., the shrinkage parameter) for the LASSO regression</p>
<p>The final set of controls is a union of controls from the LASSO regression X~C and Y~C</p>
</blockquote></li>
<li><p>Take fitted models and <strong>apply to the testing</strong> data set</p></li>
<li><p>Get all nonzero variables in C and use as controls in controlled regression of Y on X</p></li>
</ul></li>
</ul></li>
<li><p>Causal Trees/Forests</p>
<ul>
<li>Previous models assume homogeneous treatment effects. However, <strong>causal trees/forests estimates heterogeneous treatment effects</strong> where impact differs on observed criteria
<ul>
<li>Use trees (or forests) to identify partition of the demographic space that maximizes observed difference of Y between treatment and control while balancing overfitting</li>
</ul></li>
<li>Steps
<ul>
<li>Split data into two halves</li>
<li>Fit trees/forests on one half (i.e., the splitting subsample) and apply to second half (i.e., the estimating subsample) to estimate treatment effects</li>
<li>Heterogeneous treatment effects from difference in Y in leaf nodes (i.e., the treatment effect conditioned on C attributes in leaf nodes)</li>
<li>Optimization criteria set up to find the best fit given the splitting subsample</li>
<li>Forest is an average of a collection of trees with sampling</li>
</ul></li>
</ul></li>
</ul>


</section>
</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Causal</category>
  <category>Machine Learning</category>
  <guid>https://yanghaowang.github.io/posts/causal-inference-intro/</guid>
  <pubDate>Fri, 07 May 2021 03:30:32 GMT</pubDate>
</item>
</channel>
</rss>
