<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/visualizing-montecarlo-simulation-results-mean-vs-median/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://firstdifferences.wordpress.com/2018/03/15/visualizing-montecarlo-simulation-results-mean-vs-median/"> R – first differences</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Simulation studies are used in a wide range of areas from risk management, to epidemiology, and of course in statistics. The <a rel="nofollow" href="https://cran.r-project.org/web/packages/MonteCarlo/index.html" target="_blank">MonteCarlo</a> package provides tools to automatize the design of these kind of simulation studies in R. The user only has to specify the random experiment he or she wants to conduct and to specify the number of replications. The rest is handled by the package. </p>
<p>So far, the main tool to analyze the results was to look at Latex tables generated using the <em>MakeTable()</em> function. Now, the new package version 1.0.4 contains the function <em>MakeFrame()</em> that allows to represent the simulation results in form of a dataframe. This makes it very easy to visualize the results using standard tools such as <em>dplyr</em> and <em>ggplot2</em>.</p>
<p>Here, I will demonstrate some of these concepts for a simple example that could be part of an introductory statistics course: the comparison of the mean and the median as estimators for the expected value. For an introduction to the <a rel="nofollow" href="https://cran.r-project.org/web/packages/MonteCarlo/index.html" target="_blank">MonteCarlo</a> package click <a rel="nofollow" href="https://firstdifferences.wordpress.com/2017/06/08/introducing-the-montecarlo-package/" target="_blank">here</a> or confer the package <a rel="nofollow" href="https://cran.r-project.org/web/packages/MonteCarlo/vignettes/MonteCarlo-Vignette.html" target="_blank">vignette</a>.</p>
<p>For a symmetric distribution both the mean and the median are consistent estimators of the expected value, but since the mean is the maximum likelihood estimator, it is more efficient. On the other hand, it is usually stressed that in contrast to the mean, the median is not sensitive to outliers.</p>
<p>To demonstrate this, and to explore the relative magnitude of these effects depending on the sample size, we formulate a suitable random experiment. </p>
<pre><code>library(MonteCarlo)
set.seed(123)

mean_vs_median&lt;-function(n, out){

  # generate sample
  sample&lt;-rnorm(n, 0, 1)

  # add outlier
  sample[1]&lt;-sample[1]+out

  # calculate estimators
  mean_sample&lt;-mean(sample)
  median_sample&lt;-median(sample)

  # return results
  return(list(&quot;mean&quot;=mean_sample, &quot;median&quot;=median_sample))
}
</code></pre>
<p>The <em>mean_vs_median()</em> function generates a sample of <em>n</em> standard normal distributed random variables and contaminates the first observation with a deterministic outlier of size <em>out</em>. We then calculate both the mean and the median and return them as elements of a list. Note that the function has two arguments – the sample size <em>n</em> and the size of the outlier <em>out</em>. </p>
<p>To analyze the effect of these two parameters on the relative performance of the two estimators, we use the <em>MonteCarlo</em> package. All we have to do is to pass the <em>mean_vs_median</em> function to the <em>MonteCarlo()</em> function and to specify the parameter values we are interested in. In the example below, we look at outliers of size 0, 3, or 5 in a sample of size 5, 25, or 250 and the experiment is repeated 1000 times.</p>
<pre><code>erg_mean_median&lt;-MonteCarlo(func=mean_vs_median, nrep=1000, param_list=list(&quot;n&quot;=c(5, 25, 250), &quot;out&quot;=c(0, 3, 5)))
</code></pre>
<pre><code>summary(erg_mean_median)
</code></pre>
<pre><code>## Simulation of function: 
## 
## function(n, out){
## 
##   # generate sample
##   sample&lt;-rnorm(n, 0, 1)
##   
##   # add outlier
##   sample[1]&lt;-sample[1]+out
## 
##   # calculate estimators
##   mean_sample&lt;-mean(sample)
##   median_sample&lt;-median(sample)
## 
##   # return results
##   return(list(&quot;mean&quot;=mean_sample, &quot;median&quot;=median_sample))
## }
## 
## Required time: 2.61 secs for nrep = 1000  repetitions on 1 CPUs 
## 
## Parameter grid: 
## 
##    n : 5 25 250 
##  out : 0 3 10 
## 
##  
## 2 output arrays of dimensions: 3 3 1000</code></pre>
<p>This is all the programming that is required to run the simulation study. To be able to generate plots from the results we call the <em>MakeFrame()</em> function on the object returned by the simulation.</p>
<pre><code>df&lt;-MakeFrame(erg_mean_median)
head(df)
</code></pre>
<pre><code>##     n out        mean      median
## 1  25   0  0.85512352  1.28055488
## 2 250   0 -0.19633118 -0.09100042
## 3   5   0 -0.07376411 -0.06749168
## 4  25   3  0.59734761  0.59949205
## 5 250   3  0.13122706  0.28618942
## 6   5   3  0.07257960  0.12357383</code></pre>
<p>As one can see, the result is a dataframe. Each row contains information on a single repetition of the random experiment. The first two columns contain the values of the parameters and the other two columns contain the estimates of the <em>mean</em> and the <em>median</em>.</p>
<p>To manipulate the dataframe and to make plots, we load the <em>tidyverse</em> package and convert the dataframe to a <em>tibble</em>. </p>
<pre><code>library(tidyverse)
tbl &lt;- tbl_df(df)
</code></pre>
<p>To compare the efficiency of the estimates in absence of an outlier, we focus on the cases where <em>out=0</em> and then compare estimates of the distribution of the estimators for different sample sizes. For each sample size we use a different colour and the mean and the median can be distinguished by the linetypes. </p>
<pre><code>ggplot(filter(tbl, out==0)) + 
  geom_density(aes(x=mean, col=factor(n), linetype=&quot;mean&quot;)) +
  geom_density(aes(x=median, col=factor(n), linetype=&quot;median&quot;))
</code></pre>
<p><img data-orig-file="https://firstdifferences.files.wordpress.com/2018/03/unnamed-chunk-7-1.png?w=456" data-orig-size="504,504" data-medium-file="https://firstdifferences.files.wordpress.com/2018/03/unnamed-chunk-7-1.png?w=456?w=300" data-attachment-id="134" data-image-meta="{" data-image-description="" src="https://firstdifferences.files.wordpress.com/2018/03/unnamed-chunk-7-1.png?w=456" data-permalink="https://firstdifferences.wordpress.com/unnamed-chunk-7-1/" data-large-file="https://firstdifferences.files.wordpress.com/2018/03/unnamed-chunk-7-1.png?w=456?w=504" alt="unnamed-chunk-7-1" data-image-title="unnamed-chunk-7-1" sizes="(max-width: 504px) 100vw, 504px" data-comments-opened="1" class="wp-image-134" data-recalc-dims="1"></p>
<p>It is clear to see that both the distribution of the mean and the median are centered around the true expected value of zero. This implies that both estimators are unbiased. However, the distribution of the mean tends to be more concentrated than that of the median. The mean has a smaller variance and is therefore more efficient.</p>
<p>This can also be seen if we calculate the corresponding summary statistics. Using the tibble and the dplyr package, this can be done with a single line of code.</p>
<pre><code>tbl %>% filter(out==0) %>% group_by(n) %>% summarise_each(&quot;sd&quot;) %>% round(digits=2)
</code></pre>
<pre><code>## # A tibble: 3 x 4
##       n   out  mean median
##       
## 1     5     0  0.06   0.08
## 2    25     0  0.44   0.52
## 3   250     0  0.19   0.24</code></pre>
<p>We now consider the effect of outliers on the two estimators. To do so, we generate a similar plot, but now we keep the sample size constant a <em>n=25</em> and different colors represent outliers of different magnitudes.</p>
<pre><code>ggplot(filter(tbl, n==25)) + 
  geom_density(aes(x=mean, col=factor(out), linetype=&quot;mean&quot;)) +
  geom_density(aes(x=median, col=factor(out), linetype=&quot;median&quot;))
</code></pre>
<p><img data-orig-file="https://firstdifferences.files.wordpress.com/2018/03/unnamed-chunk-9-1.png?w=456" data-orig-size="504,504" data-medium-file="https://firstdifferences.files.wordpress.com/2018/03/unnamed-chunk-9-1.png?w=456?w=300" data-attachment-id="135" data-image-meta="{" data-image-description="" src="https://firstdifferences.files.wordpress.com/2018/03/unnamed-chunk-9-1.png?w=456" data-permalink="https://firstdifferences.wordpress.com/unnamed-chunk-9-1/" data-large-file="https://firstdifferences.files.wordpress.com/2018/03/unnamed-chunk-9-1.png?w=456?w=504" alt="unnamed-chunk-9-1" data-image-title="unnamed-chunk-9-1" sizes="(max-width: 504px) 100vw, 504px" data-comments-opened="1" class="wp-image-135" data-recalc-dims="1"></p>
<p>It is clear to see that the dashed lines representing the distribution of the medians are centered around the true mean of zero, irrespective of the size of the outlier. The distribution of the means, on the other hand, shifts further to the right the larger the magnitude of the outlier. This shows that the median is robust to outliers, whereas the mean is not.</p>
<p>Finally, we want to explore the interaction of the effect of the size of the outlier with the sample size. We therefore focus on the mean. Different colors now represent different sizes of the outlier and different linetypes represent different sample sizes.</p>
<pre><code>ggplot(filter(tbl)) + 
  geom_density(aes(x=mean, col=factor(out), linetype=factor(n)))
</code></pre>
<p><img data-orig-file="https://firstdifferences.files.wordpress.com/2018/03/unnamed-chunk-10-1.png?w=456" data-orig-size="504,504" data-medium-file="https://firstdifferences.files.wordpress.com/2018/03/unnamed-chunk-10-1.png?w=456?w=300" data-attachment-id="136" data-image-meta="{" data-image-description="" src="https://firstdifferences.files.wordpress.com/2018/03/unnamed-chunk-10-1.png?w=456" data-permalink="https://firstdifferences.wordpress.com/unnamed-chunk-10-1/" data-large-file="https://firstdifferences.files.wordpress.com/2018/03/unnamed-chunk-10-1.png?w=456?w=504" alt="unnamed-chunk-10-1" data-image-title="unnamed-chunk-10-1" sizes="(max-width: 504px) 100vw, 504px" data-comments-opened="1" class="wp-image-136" data-recalc-dims="1"></p>
<p>For an outlier of a given size, we can observe that its impact decreases as the sample size increases. While the effect of the outlier can be quite dramatic for <em>n=5</em>, the effect basically vanishes for <em>n=250</em>. The sensitivity of the mean to outliers is therefore a finite sample property that is less important in larger samples.</p>
<p>As can be seen from this example, conducting simulation studies requires minimal effort, if a package such as <em>MonteCarlo</em> or one of its competitors such as <em>simsalapar</em> or <em>SimDesign</em> is used. The programming required to produce this analysis should be simple enough so that simulations are not restricted to be a tool for research, but can even be used for teaching at an undergraduate level.</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="https://firstdifferences.wordpress.com/2018/03/15/visualizing-montecarlo-simulation-results-mean-vs-median/"> R – first differences</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 alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/uwPKg-ZV2lg" height="1"></a></div>