<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/sampling-distribution-of-weighted-gini-coefficient-by-ellis2013nz/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://ellisp.github.io/blog/2017/08/05/weighted-gini"> Peter's stats stuff - R</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<h2>Calculating Gini coefficients</h2>
<p>Stats NZ release a series of working papers, and a recent one caught my eye because of my interest in inequality statistics (disclaimer – I am working at Stats NZ at the moment, but on completely different things). Working Paper No 17–02 by Vic Duoba and Nairn MacGibbon is on <a rel="nofollow" href="http://www.stats.govt.nz/methods/research-papers/working-papers-original/calc-gini-index-17-02.aspx" target="_blank">Accurate calculation of a Gini index using SAS and R</a>. While the conceptual definition of a Gini coefficient is well known, there are a few different methods out there for estimating one from finite data.</p>
<p>To refresh memories, a Gini coefficient is defined as the ratio A / (A +B) in the diagram below, which is drawn with simulated data I’ll introduce later in the post:</p>
<p><img width="100%" src="http://ellisp.github.io/img/0106-lorenz.svg"></p>
<p>In a situation of perfect equality (everyone has the same income, or whatever it is we are measuring inequality of) the Lorenz curve <em>is</em> the diagonal line, and A is 0 so the Gini coefficient is 0. In a situation where the richest person has <em>all</em> the income and everyone else none, the Lorenz curve is horizontal along the bottom of the chart and spikes up to 1 at the extreme right – so B is 0 and the Gini coefficient is 1. Income Gini coefficients are usually calculated on household incomes, and according to Wikipedia they range from <a rel="nofollow" href="https://en.wikipedia.org/wiki/List_of_countries_by_income_equality" target="_blank">0.24 (Slovenia) to 0.63 (Lesotho)</a>. My simulated data above is meant to represent <em>individual</em> income, which is higher than household income in situations where significant numbers of low income individuals live with higher income people.</p>
<p>Duoba and MacGibbon do a brief review of algorithms and choose a preferred one, noting along the way that the existing Stats NZ method will underestimate inequality (very, very slightly – this isn’t something that should make the news please, it’s the fourth decimal place). They helpfully provide a SAS program to implement the algorithm which is literally two pages long, and a much shorter R program that is half a page.</p>
<h3>Q1. Is <code>acid::weighted.gini()</code> using the best method?</h3>
<p>Of course, shorter, more readable, and more mathematically-oriented (ie vectorized) code is one reason I prefer R to SAS. But another reason is that nearly any functionality one can imagine for published techniques already has an implementation out there we can borrow. In this respect, pitting R against SAS is simply no contest; it’s like <a rel="nofollow" href="https://en.wikipedia.org/wiki/Wikipedia:Size_comparisons" target="_blank">Wikipedia versus an encyclopedia written by a single organisation</a>. Wikipedia has 5.5 million articles in English, Britannica’s last hard copy had 40,000 (and the online edition has 120,000, but I think the hard copy is somehow more like SAS, if I’m not pushing the metaphor too far). The R universe quite simply has vastly more functionality available to it than is ready off the shelf for SAS users.</p>
<p>So while Duoba and MacGibbon’s 20 effective lines of R is preferable to 90 lines of SAS, even more convenient is to just use the one liner <code>acid::weighted.gini(x, w)</code>, using free user contributions to the R universe.</p>
<p>With choice comes uncertainty. I did want to check that the method I’ve been using for calculating Gini coefficients from weighted data (like in <a rel="nofollow" href="http://ellisp.github.io/blog/2017/07/22/inter-country-inequality" target="_blank">this post on inter-country inequality</a>) matched the one recommended by Duoba and MacGibbon. I used the <code>weighted.gini</code> function from <a rel="nofollow" href="https://cran.r-project.org/package=acid" target="_blank">Alexander Sohn (2016). acid: Analysing Conditional Income Distributions. R package version<br>
1.1.</a>.</p>
<p>First, here’s code setting up the session and creating Duoba and MacGibbon’s <code>StatsGini</code> R function:</p>
<figure>
<pre><code data-lang="r"><span>library</span><span>(</span><span>tidyverse</span><span>)</span><span>
</span><span>library</span><span>(</span><span>acid</span><span>)</span><span>
</span><span>library</span><span>(</span><span>microbenchmark</span><span>)</span><span>
</span><span>library</span><span>(</span><span>forcats</span><span>)</span><span>
</span><span># Peter's Stats Stuff miscellaneous stuff package, install with: </span><span>devtools</span><span>::</span><span>install_github</span><span>(</span><span>&quot;ellisp/pssmisc-r-package/pkg&quot;</span><span>)</span><span>
</span><span>library</span><span>(</span><span>pssmisc</span><span>)</span><span> </span><span># Duoba and MacGibbon's function, reproduced as in the original paper:
</span><span>StatsGini</span><span> </span><span>&lt;-</span><span> </span><span>function</span><span>(</span><span>x</span><span>,</span><span> </span><span>w</span><span> </span><span>=</span><span> </span><span>rep</span><span>(</span><span>1</span><span>,</span><span> </span><span>length</span><span>(</span><span>x</span><span>))){</span><span>
</span><span># x and w are vectors
</span><span> </span><span># w can be left blank when calling the fn (i.e. no weighting)
</span><span> </span><span># Examples:
</span><span> </span><span># x &lt;-c(3, 1, 7, 2, 5)
</span><span> </span><span># w &lt;-c(1, 2, 3, 4, 5)
</span><span> </span><span># StatsGini(x, w) should yield 0.2983050847
</span><span> </span><span># StatsGini(c(0.25, 0.75), c(1, 1)) should yield 0.25
</span><span> </span><span>n</span><span> </span><span>&lt;-</span><span> </span><span>length</span><span>(</span><span>x</span><span>)</span><span>
</span><span>wxsum</span><span> </span><span>&lt;-</span><span> </span><span>sum</span><span>(</span><span>w</span><span> </span><span>*</span><span> </span><span>x</span><span>)</span><span>
</span><span>wsum</span><span> </span><span>&lt;-</span><span> </span><span>sum</span><span>(</span><span>w</span><span>)</span><span>
</span><span>sxw</span><span> </span><span>&lt;-</span><span> </span><span>order</span><span>(</span><span>x</span><span>,</span><span> </span><span>w</span><span>)</span><span> </span><span># Ascending order sort
</span><span> </span><span>sx</span><span> </span><span>&lt;-</span><span> </span><span>w</span><span>[</span><span>sxw</span><span>]</span><span> </span><span>*</span><span> </span><span>x</span><span>[</span><span>sxw</span><span>]</span><span>
</span><span>sw</span><span> </span><span>&lt;-</span><span> </span><span>w</span><span>[</span><span>sxw</span><span>]</span><span>
</span><span>pxi</span><span> </span><span>&lt;-</span><span> </span><span>vector</span><span>(</span><span>mode</span><span> </span><span>=</span><span> </span><span>&quot;numeric&quot;</span><span>,</span><span> </span><span>length</span><span> </span><span>=</span><span> </span><span>n</span><span>)</span><span>
</span><span>pci</span><span> </span><span>&lt;-</span><span> </span><span>vector</span><span>(</span><span>mode</span><span> </span><span>=</span><span> </span><span>&quot;numeric&quot;</span><span>,</span><span> </span><span>length</span><span> </span><span>=</span><span> </span><span>n</span><span>)</span><span>
</span><span>pxi</span><span> </span><span>&lt;-</span><span> </span><span>cumsum</span><span>(</span><span>sx</span><span>)</span><span> </span><span>/</span><span> </span><span>wxsum</span><span>
</span><span>pci</span><span> </span><span>&lt;-</span><span> </span><span>cumsum</span><span>(</span><span>sw</span><span>)</span><span> </span><span>/</span><span> </span><span>wsum</span><span>
</span><span>G</span><span> </span><span>&lt;-</span><span> </span><span>0.0</span><span>
</span><span>for</span><span> </span><span>(</span><span>i</span><span> </span><span>in</span><span> </span><span>2</span><span>:</span><span>n</span><span>){</span><span>
</span><span>G</span><span> </span><span>&lt;-</span><span> </span><span>G</span><span> </span><span>-</span><span> </span><span>(</span><span>pci</span><span>[</span><span>i</span><span>]</span><span> </span><span>*</span><span> </span><span>pxi</span><span>[</span><span>i</span><span> </span><span>-</span><span> </span><span>1</span><span>]</span><span> </span><span>-</span><span> </span><span>pxi</span><span>[</span><span>i</span><span>]</span><span> </span><span>*</span><span> </span><span>pci</span><span>[</span><span>i</span><span> </span><span>-</span><span> </span><span>1</span><span>]</span><span> </span><span>)</span><span>
</span><span>}</span><span>
</span><span>return</span><span>(</span><span>G</span><span>)</span><span>
</span><span>}</span></code></pre>
</figure>
<p>And here’s some checks. We see to 10 decimal places, using the toy examples provided by Stats NZ, we get identical results:</p>
<div>
<pre><code>> options(digits = 10)
> x &lt;- c(3, 1, 7, 2, 5)
> w &lt;- c(1, 2, 3, 4, 5)
> StatsGini(x, w) # should yield 0.2983050847
[1] 0.2983050847
> StatsGini(c(0.25, 0.75), c(1, 1)) # should yield 0.25
[1] 0.25
> weighted.gini(x, w)
$Gini
             [,1]
[1,] 0.2983050847

> weighted.gini(c(0.25, 0.75), c(1, 1))
$Gini
     [,1]
[1,] 0.25

</code></pre>
</div>
<p>Tests with more complicated data showed identical results too but I won’t bore the reader with them.</p>
<h3>A realistic individual income simulation</h3>
<p>Next, I wanted to try out the two functions on some realistic data. Individual income data typically has a very complex distribution that is best thought of as a mixture of at least three distributions. There is usually a spike at zero for zero income individuals, a smattering of people with negative incomes, and then a mixture of skewed distributions for positive incomes. Typically, <em>heavily</em> skewed, like a log-Normal distribution with bonus outliers – there are a small number of very high income individuals out there.</p>
<p>To simulate the data in the Lorenz curve graphic I started with, I used the function below. It implements a mixture of log-t distributions (using t rather than Normal because of the longer tails) ie e to the power of a variable from a mix of t distributions. The mean of those t distributions itself is a random variable, in this case a non-transformed t distribution. Then each value is multiplied at random by -1, 0 or 1 to simulate the idiosyncratic negative, zero, positive nature of incomes.</p>
<p>When I create the data frame with 100,000 incomes in it, I also create a column called <code>prob</code> with randomly generated numbers between 0 and 1 following a Beta(2, 2) distribution. I’m going to use that later to simulate the experience of sampling individuals for a complex survey.</p>
<figure>
<pre><code data-lang="r"><span>#' Generate a realistic mixed distribution of incomes
#'
#' alpha ~ t(d_alpha) scaled to mean, sd of (log(mu), sigma_alpha)
#' beta ~ t(d_beta) scaled to mean, sd of (alpha, sigma_beta)
#' x = exp(beta)
#' y = x * I(-1, 0, 1)
#'
#' @param n sample size to generate
#' @param mu median income
#' @param sigma_alpha standard deviation of underlying latent means
#' @param sigma_beta standard deviation of scaled t distribution underlying the population's log-t distribution
#' @param d_alpha degrees of freedom in th
#' @param d_beta degrees of freedom in the t distribution underlying the log-t
#' @param pr vector of 2 elements, the probability of negative income and of zero income respectively
</span><span>gen_incomes</span><span> </span><span>&lt;-</span><span> </span><span>function</span><span>(</span><span>n</span><span>,</span><span> </span><span>mu</span><span> </span><span>=</span><span> </span><span>30000</span><span>,</span><span> </span><span>sigma_alpha</span><span> </span><span>=</span><span> </span><span>1</span><span>,</span><span> </span><span>sigma_beta</span><span> </span><span>=</span><span> </span><span>1</span><span>,</span><span> </span><span>d_alpha</span><span> </span><span>=</span><span> </span><span>15</span><span>,</span><span> </span><span>d_beta</span><span> </span><span>=</span><span> </span><span>15</span><span>,</span><span>
</span><span>pr</span><span> </span><span>=</span><span> </span><span>c</span><span>(</span><span>0.01</span><span>,</span><span> </span><span>0.2</span><span>)){</span><span>
</span><span>alpha</span><span> </span><span>&lt;-</span><span> </span><span>rt</span><span>(</span><span>n</span><span>,</span><span> </span><span>d_alpha</span><span>)</span><span> </span><span>*</span><span> </span><span>sigma_alpha</span><span> </span><span>+</span><span> </span><span>log</span><span>(</span><span>mu</span><span>)</span><span>
</span><span>beta</span><span> </span><span>&lt;-</span><span> </span><span>exp</span><span>(</span><span>rt</span><span>(</span><span>n</span><span>,</span><span> </span><span>d_beta</span><span>)</span><span> </span><span>*</span><span> </span><span>sigma_beta</span><span> </span><span>+</span><span> </span><span>alpha</span><span>)</span><span>
</span><span>y</span><span> </span><span>&lt;-</span><span> </span><span>beta</span><span> </span><span>*</span><span> </span><span>sample</span><span>(</span><span>c</span><span>(</span><span>-1</span><span>,</span><span> </span><span>0</span><span>,</span><span> </span><span>1</span><span>),</span><span> </span><span>n</span><span>,</span><span> </span><span>replace</span><span> </span><span>=</span><span> </span><span>TRUE</span><span>,</span><span> </span><span>prob</span><span> </span><span>=</span><span> </span><span>c</span><span>(</span><span>pr</span><span>,</span><span> </span><span>1</span><span> </span><span>-</span><span> </span><span>sum</span><span>(</span><span>pr</span><span>)))</span><span>
</span><span>return</span><span>(</span><span>y</span><span>)</span><span>
</span><span>}</span><span>
</span><span>set.seed</span><span>(</span><span>123</span><span>)</span><span>
</span><span>N</span><span> </span><span>&lt;-</span><span> </span><span>100000</span><span>
</span><span>population</span><span> </span><span>&lt;-</span><span> </span><span>data.frame</span><span>(</span><span>income</span><span> </span><span>=</span><span> </span><span>gen_incomes</span><span>(</span><span>N</span><span>),</span><span> </span><span>sigma_alpha</span><span> </span><span>=</span><span> </span><span>1</span><span>,</span><span> </span><span>d_alpha</span><span> </span><span>=</span><span> </span><span>10</span><span>,</span><span> </span><span>d_beta</span><span> </span><span>=</span><span> </span><span>150</span><span>,</span><span>
</span><span>sigma_beta</span><span> </span><span>=</span><span> </span><span>2</span><span>,</span><span>
</span><span>prob</span><span> </span><span>=</span><span> </span><span>rbeta</span><span>(</span><span>N</span><span>,</span><span> </span><span>2</span><span>,</span><span> </span><span>2</span><span>))</span><span>
</span><span># draw density plot with a slice of 1000 people:
</span><span>population</span><span> </span><span>%>%</span><span>
</span><span>slice</span><span>(</span><span>1</span><span>:</span><span>1000</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>ggplot</span><span>(</span><span>aes</span><span>(</span><span> </span><span>x</span><span> </span><span>=</span><span> </span><span>income</span><span>))</span><span> </span><span>+</span><span> </span><span>scale_x_continuous</span><span>(</span><span>&quot;Annual income (modulus transform with power of 0.02)&quot;</span><span>,</span><span>
</span><span>label</span><span> </span><span>=</span><span> </span><span>dollar</span><span>,</span><span> </span><span>trans</span><span> </span><span>=</span><span> </span><span>modulus_trans</span><span>(</span><span>0.02</span><span>),</span><span>
</span><span>breaks</span><span> </span><span>=</span><span> </span><span>modulus_breaks</span><span>(</span><span>lambda</span><span> </span><span>=</span><span> </span><span>0.02</span><span>))</span><span> </span><span>+</span><span> </span><span>geom_density</span><span>(</span><span>fill</span><span> </span><span>=</span><span> </span><span>&quot;grey&quot;</span><span>,</span><span> </span><span>alpha</span><span> </span><span>=</span><span> </span><span>0.2</span><span>)</span><span> </span><span>+</span><span>
</span><span>geom_rug</span><span>()</span><span> </span><span>+</span><span>
</span><span>ggtitle</span><span>(</span><span>&quot;Density of simulated annual incomes&quot;</span><span>,</span><span>
</span><span>&quot;First 1,000 values&quot;</span><span>)</span></code></pre>
</figure>
<p>This is what that looks like:</p>
<p><img width="100%" src="http://ellisp.github.io/img/0106-density.svg"></p>
<p>I wrote about the modulus transform, used in the horizontal axis in that chart, in <a rel="nofollow" href="http://ellisp.github.io/blog/2015/09/05/creating-a-scale-transformation" target="_blank">earlier blog posts</a>. It’s an idea put forward by John and Draper in 1980 that I’m surprised hasn’t taken off more. It’s very similar to a Box-Cox power transform, but it works for values of 0 and negative values too. It does something very similar to a Box-Cox transform to the absolute value of the data, then returns the sign to it. It’s a much, much better answer than the commonly used alternatives to what to do with data that looks like it needs a log transformation but inconveniently has some zeros and negatives. I’ve implemented methods to do this in my new <code>pssmisc</code> ad hoc R package, referenced earlier in the code.</p>
<p>For completeness, here’s the code that drew the Lorenz curve diagram at the top of the post:</p>
<figure>
<pre><code data-lang="r"><span>population</span><span> </span><span>%>%</span><span>
</span><span># thin down to just a sample of 10,000 to save on vector graphic file size:
</span><span> </span><span>sample_n</span><span>(</span><span>10000</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>arrange</span><span>(</span><span>income</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>mutate</span><span>(</span><span>cum_prop_inc</span><span> </span><span>=</span><span> </span><span>cumsum</span><span>(</span><span>income</span><span>)</span><span> </span><span>/</span><span> </span><span>sum</span><span>(</span><span>income</span><span>),</span><span>
</span><span>seq</span><span> </span><span>=</span><span> </span><span>1</span><span>:</span><span>n</span><span>()</span><span> </span><span>/</span><span> </span><span>n</span><span>())</span><span> </span><span>%>%</span><span>
</span><span>ggplot</span><span>(</span><span>aes</span><span>(</span><span>x</span><span> </span><span>=</span><span> </span><span>seq</span><span>,</span><span> </span><span>y</span><span> </span><span>=</span><span> </span><span>cum_prop_inc</span><span>))</span><span> </span><span>+</span><span>
</span><span>geom_line</span><span>()</span><span> </span><span>+</span><span>
</span><span>geom_ribbon</span><span>(</span><span>aes</span><span>(</span><span>ymax</span><span> </span><span>=</span><span> </span><span>seq</span><span>,</span><span> </span><span>ymin</span><span> </span><span>=</span><span> </span><span>cum_prop_inc</span><span>),</span><span> </span><span>fill</span><span> </span><span>=</span><span> </span><span>&quot;steelblue&quot;</span><span>,</span><span> </span><span>alpha</span><span> </span><span>=</span><span> </span><span>0.2</span><span>)</span><span> </span><span>+</span><span>
</span><span>geom_abline</span><span>(</span><span>intercept</span><span> </span><span>=</span><span> </span><span>0</span><span>,</span><span> </span><span>slope</span><span> </span><span>=</span><span> </span><span>1</span><span>,</span><span> </span><span>colour</span><span> </span><span>=</span><span> </span><span>&quot;steelblue&quot;</span><span>)</span><span> </span><span>+</span><span>
</span><span>labs</span><span>(</span><span>x</span><span> </span><span>=</span><span> </span><span>&quot;Cumulative proportion of population, from poorest to richest&quot;</span><span>,</span><span>
</span><span>y</span><span> </span><span>=</span><span> </span><span>&quot;Cumulative proportion of income&quot;</span><span>)</span><span> </span><span>+</span><span>
</span><span>annotate</span><span>(</span><span>&quot;text&quot;</span><span>,</span><span> </span><span>x</span><span> </span><span>=</span><span> </span><span>c</span><span>(</span><span>0.6</span><span>,</span><span> </span><span>0.95</span><span>),</span><span> </span><span>y</span><span> </span><span>=</span><span> </span><span>c</span><span>(</span><span>0.4</span><span>,</span><span> </span><span>0.05</span><span>),</span><span> </span><span>label</span><span> </span><span>=</span><span> </span><span>c</span><span>(</span><span>&quot;A&quot;</span><span>,</span><span> </span><span>&quot;B&quot;</span><span>),</span><span> </span><span>size</span><span> </span><span>=</span><span> </span><span>7</span><span>)</span><span> </span><span>+</span><span>
</span><span>annotate</span><span>(</span><span>&quot;text&quot;</span><span>,</span><span> </span><span>x</span><span> </span><span>=</span><span> </span><span>0.5</span><span>,</span><span> </span><span>y</span><span> </span><span>=</span><span> </span><span>0.6</span><span>,</span><span> </span><span>label</span><span> </span><span>=</span><span> </span><span>&quot;Line of equality&quot;</span><span>,</span><span> </span><span>angle</span><span> </span><span>=</span><span> </span><span>45</span><span>)</span><span> </span><span>+</span><span>
</span><span>annotate</span><span>(</span><span>&quot;text&quot;</span><span>,</span><span> </span><span>x</span><span> </span><span>=</span><span> </span><span>0.85</span><span>,</span><span> </span><span>y</span><span> </span><span>=</span><span> </span><span>0.15</span><span>,</span><span> </span><span>label</span><span> </span><span>=</span><span> </span><span>&quot;Actual distribution&quot;</span><span>,</span><span> </span><span>angle</span><span> </span><span>=</span><span> </span><span>45</span><span>)</span><span> </span><span>+</span><span>
</span><span>coord_equal</span><span>()</span><span> </span><span>+</span><span>
</span><span>ggtitle</span><span>(</span><span>&quot;Lorenz curve with simulated income data&quot;</span><span>,</span><span>
</span><span>paste</span><span>(</span><span>&quot;Gini coefficient is&quot;</span><span>,</span><span> </span><span>round</span><span>(</span><span>gini</span><span>(</span><span>population</span><span>$</span><span>income</span><span>)</span><span>$</span><span>Gini</span><span>,</span><span> </span><span>2</span><span>)))</span></code></pre>
</figure>
<h3>Q2. Is acid:weighted.gini more or less efficient than the StatsNZ alternative?</h3>
<p>Next I wanted to try out the efficiency of the two functions. To do this I gave them a tougher job – estimate the Gini coefficient for the whole population of 100,000, but using the inverse of the <code>prob</code> column as weights. The <code>microbenchmark</code> package making it easy to do this 1,000 times for a reliable estimate, and even gives an automatic <code>ggplot2</code> method.</p>
<figure>
<pre><code data-lang="r"><span>y</span><span> </span><span>&lt;-</span><span> </span><span>population</span><span>$</span><span>income</span><span>
</span><span>w</span><span> </span><span>&lt;-</span><span> </span><span>1</span><span>/</span><span> </span><span>population</span><span>$</span><span>prob</span><span>
</span><span>mb</span><span> </span><span>&lt;-</span><span> </span><span>microbenchmark</span><span>(</span><span>
</span><span>weighted.gini</span><span>(</span><span>y</span><span>,</span><span> </span><span>w</span><span>)</span><span>$</span><span>Gini</span><span>,</span><span>
</span><span>StatsGini</span><span>(</span><span>y</span><span>,</span><span> </span><span>w</span><span>),</span><span>
</span><span>times</span><span> </span><span>=</span><span> </span><span>1000</span><span>)</span><span>
</span><span>autoplot</span><span>(</span><span>mb</span><span>,</span><span> </span><span>log</span><span> </span><span>=</span><span> </span><span>FALSE</span><span>)</span><span> </span><span>+</span><span>
</span><span>ggtitle</span><span>(</span><span>&quot;Time taken to estimated Gini coefficient from 100,000 observations&quot;</span><span>,</span><span>
</span><span>&quot;Microbenchmark results&quot;</span><span>)</span><span> </span></code></pre>
</figure>
<p>With these results:</p>
<p><img width="100%" src="http://ellisp.github.io/img/0106-benchmark.svg"></p>
<p>The method in <code>acid::weighted.gini</code> is slightly faster than is <code>StatsGini</code>. <code>acid</code> uses matrix multiplication for a calculation that <code>StatsGini</code> does through a <code>for</code> loop, which explains the difference. It’s not a big deal though, and both functions reliably taking less than 50 millionths of a second to do the calculation on a sample size of 100,000.</p>
<h3>Q3. What does the sampling distribution of Gini from a weighted complex survey sample look like?</h3>
<p>Finally, I had a more substantive question of interest from a statistical point of view. In the real world, we have finite samples to estimate inequality from and our estimate of Gini coefficient will be random; it will have a sampling distribution. The samples often come from a complex survey design, which complicates the estimation process and changes the sampling distribtuion. Allowing for data from sources like a complex survey is why both calculation methods allow for a vector of unequal weights, which in this context would normally be calculated by a method such as the inverse probability of an population member being in the sample.</p>
<p>I’ve looked previously at the <a rel="nofollow" href="http://ellisp.github.io/blog/2015/09/12/inequality-stats-distributions" target="_blank">sampling distribution of Gini coefficient</a>, but only with unweighted data. Reading Duoba and MacGibbon’s paper reminded me that I should probably look at the realistic situation of estimating Gini coefficient with weighted data from a complex survey.</p>
<p>To do this in a pragmatic way, I simulated surveys with a range of sample sizes by creating multiple unequally probability random samples from my population of 100,000. This doesn’t really re-create the experience of a complex survey because I haven’t got primary sampling units and intra-class correlation (which make estimation harder and sampling distributions wider), but it is a start for illustrative/exploratory purposes. I calculated the weighted Gini coefficient for each and kept the results. When we plot the distributions of all these efforts to estimate the population total (which we know is really 0.82) we get the following:</p>
<p><img width="100%" src="http://ellisp.github.io/img/0106-sample-distributions.svg"></p>
<p>I truncated the horizontal axes (but not the density estimations) because there were a few very bad estimates from the smaller sample sizes – as high as 1.5 – that made the visual comparison difficult. How can a Gini coefficient be greater than 1? When there are enough negative incomes.</p>
<p>We see that a sample size of 500 isn’t too bad, with most estimates coming out between 0.7 and 0.9. But even with a sample of 10,000 there’s quite a bit of variation in the Gini coefficient of the sample. Lesson – don’t rely too much on the decimal points in inequality data coming from samples (and that’s without even getting into the other formidable measurement problems with economic data).</p>
<p>Here’s the code for the simulation:</p>
<figure>
<pre><code data-lang="r"><span># number of repeats at each sample size:
</span><span>reps</span><span> </span><span>&lt;-</span><span> </span><span>100</span><span>
</span><span># sample sizes, chosen to resemble realistic survey sizes:
</span><span>ns</span><span> </span><span>&lt;-</span><span> </span><span>c</span><span>(</span><span>30</span><span>,</span><span> </span><span>100</span><span>,</span><span> </span><span>500</span><span>,</span><span> </span><span>1000</span><span>,</span><span> </span><span>3000</span><span>,</span><span> </span><span>10000</span><span>)</span><span>
</span><span># matrix of zeros that we'll replace with the estimates of Gini
</span><span>res</span><span> </span><span>&lt;-</span><span> </span><span>matrix</span><span>(</span><span>0</span><span>,</span><span> </span><span>nrow</span><span> </span><span>=</span><span> </span><span>reps</span><span>,</span><span> </span><span>ncol</span><span> </span><span>=</span><span> </span><span>length</span><span>(</span><span>ns</span><span>))</span><span>
</span><span># obviously this next bit could be made much more efficient by parallel processing,
# but it's only a few minutes of running </span><span>set.seed</span><span>(</span><span>666</span><span>)</span><span>
</span><span>for</span><span>(</span><span>i</span><span> </span><span>in</span><span> </span><span>1</span><span>:</span><span>length</span><span>(</span><span>ns</span><span>)){</span><span>
</span><span>n</span><span> </span><span>&lt;-</span><span> </span><span>ns</span><span>[</span><span>i</span><span>]</span><span>
</span><span>for</span><span>(</span><span>j</span><span> </span><span>in</span><span> </span><span>1</span><span>:</span><span>reps</span><span>){</span><span>
</span><span>the_sample</span><span> </span><span>&lt;-</span><span> </span><span>sample_n</span><span>(</span><span>population</span><span>,</span><span> </span><span>size</span><span> </span><span>=</span><span> </span><span>n</span><span>,</span><span> </span><span>replace</span><span> </span><span>=</span><span> </span><span>FALSE</span><span>,</span><span> </span><span>weight</span><span> </span><span>=</span><span> </span><span>population</span><span>$</span><span>prob</span><span>)</span><span> </span><span>res</span><span>[</span><span>j</span><span>,</span><span> </span><span>i</span><span>]</span><span> </span><span>&lt;-</span><span> </span><span>weighted.gini</span><span>(</span><span>the_sample</span><span>$</span><span>income</span><span>,</span><span> </span><span>w</span><span> </span><span>=</span><span> </span><span>1</span><span> </span><span>/</span><span> </span><span>the_sample</span><span>$</span><span>prob</span><span>)</span><span>$</span><span>Gini</span><span>
</span><span>}</span><span>
</span><span>}</span><span>
</span><span>res_df</span><span> </span><span>&lt;-</span><span> </span><span>as.data.frame</span><span>(</span><span>res</span><span>)</span><span>
</span><span>names</span><span>(</span><span>res_df</span><span>)</span><span> </span><span>&lt;-</span><span> </span><span>format</span><span>(</span><span>ns</span><span>,</span><span> </span><span>big.mark</span><span> </span><span>=</span><span> </span><span>&quot;,&quot;</span><span>)</span><span>
</span><span>res_df</span><span> </span><span>%>%</span><span>
</span><span>gather</span><span>(</span><span>sample_size</span><span>,</span><span> </span><span>value</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>mutate</span><span>(</span><span>sample_size</span><span> </span><span>=</span><span> </span><span>fct_reorder</span><span>(</span><span>sample_size</span><span>,</span><span> </span><span>-</span><span>value</span><span>))</span><span> </span><span>%>%</span><span>
</span><span>ggplot</span><span>(</span><span>aes</span><span>(</span><span>x</span><span> </span><span>=</span><span> </span><span>value</span><span>))</span><span> </span><span>+</span><span>
</span><span>facet_wrap</span><span>(</span><span>~</span><span>sample_size</span><span>)</span><span> </span><span>+</span><span>
</span><span>geom_density</span><span>(</span><span>alpha</span><span> </span><span>=</span><span> </span><span>0.3</span><span>,</span><span> </span><span>fill</span><span> </span><span>=</span><span> </span><span>&quot;grey&quot;</span><span>)</span><span> </span><span>+</span><span>
</span><span># a few values of > 1 make no sense and warp the graph:
</span><span> </span><span>coord_cartesian</span><span>(</span><span>xlim</span><span> </span><span>=</span><span> </span><span>c</span><span>(</span><span>0.6</span><span>,</span><span> </span><span>1</span><span>))</span><span> </span><span>+</span><span>
</span><span>labs</span><span>(</span><span>x</span><span> </span><span>=</span><span> </span><span>&quot;Estimated weighted Gini&quot;</span><span>)</span><span> </span><span>+</span><span>
</span><span>ggtitle</span><span>(</span><span>&quot;Sampling distribution of weighted Gini point estimate from a complex survey&quot;</span><span>,</span><span>
</span><span>paste0</span><span>(</span><span>&quot;Various sample sizes; true value is &quot;</span><span>,</span><span> </span><span>round</span><span>(</span><span>weighted.gini</span><span>(</span><span>population</span><span>$</span><span>income</span><span>)</span><span>$</span><span>Gini</span><span>,</span><span> </span><span>2</span><span>)))</span></code></pre>
</figure>
<p>Finished for today.</p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://ellisp.github.io/blog/2017/08/05/weighted-gini"> Peter's stats stuff - R</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/VgdKJr4_ee4" height="1"></a></div>