<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/introducing-the-montecarlo-package/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://firstdifferences.wordpress.com/2017/06/08/introducing-the-montecarlo-package/"> R – first differences</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>My first R package has been released on CRAN recently. It is named <a rel="nofollow" href="https://cran.r-project.org/web/packages/MonteCarlo/index.html" target="_blank">MonteCarlo</a> and aims to make simulation studies as easy as possible – including parallelization and the generation of tables.</p>
<h2>What Are Simulation Studies Good For?</h2>
<p>Monte Carlo simulations are an essential tool in statistics and related disciplines. They are routinely used to determine distributional properties, where no analytical results are available. A typical example is to study the finite sample properties of a new statistical procedure. Finite sample properties are often unknown, since theoretical results usually rely on asymptotic theory that only applies to infinite sample sizes. This may be a good approximation in practice if the sample size is large, but it may also be bad if the sample is small or if the rate of convergence is very slow.</p>
<p>Simulation studies are also extremely useful to compare the performance of alternative procedures for the same task. Imagine you want to test whether your sample comes from a Gaussian distribution and you have to decide whether to use the Jarque-Bera test or the Kolmogorov Smirnov test. Both appear to be legitimate choices. A simulation study that is tailored so that it reflects the situation at hand might uncover that one of the procedures is much more powerful than the other.</p>
<p>Finally, small scale simulation studies are an essential tool for statistical programming. Testing is an essential part of programming and software development. Usually, if one writes a function, it is good practice to let it run on some test cases. This is easy, if the outcome is deterministic. But if your function is a statistical test or an estimator, the output depends on the sample and is stochastic. Therefore, the only way to test whether the implementation is correct, is to generate a large number of samples and to see whether it has the expected statistical properties. For example one might test whether the mean squared error of an estimator converges to zero as the sample size increases, or whether the test has the correct alpha error.</p>
<p>Therefore, writing Monte Carlo simulations is an everyday task in many areas of statistics. This comes with considereable effort. It is not unusual that the required lines of code to produce a simulation study are a multiple of that needed to implement the procedure of interest. As a consequence of that they are also one of the main sources for errors. On top of this, the large computational effort often requires parallelization which brings additional complications and programming efforts. This efforts can often be prohibitive – especially for less advanced users.</p>
<h2>The MonteCarlo Package</h2>
<p>The MonteCarlo package streamlines the process described above. It allows to create simulation studies and to summarize their results in LaTeX tables quickly and easily.</p>
<p>There are only two main functions in the package:</p>
<ol>
<li><em>MonteCarlo()</em> runs a simulation study for a user defined parameter grid. It handles the generation of loops over these parameter grid and parallelizes the computation on a user specified number of CPU units.</li>
<li><em>MakeTable()</em> creates LaTeX tables from the output of <em>MonteCarlo()</em>. It stacks high dimensional output arrays into tables with a user specified ordering of rows and columns.</li>
</ol>
<p>To run a simulation study, the user has to nest both – the generation of a sample and the calculation of the desired statistics from this sample – in a single function. This function is passed to <em>MonteCarlo()</em>. No additional programming is required. This approach is not only very versatile – it is also very intuitive. The user formulates his experiment as if he/she was only interested in a single draw.</p>
<p>The aim of this approach is to allow the user full control and flexibility with regard to the design of the Monte Carlo experiment, but to take away all the effort of setting up the technical part of the simulation.</p>
<h2>A Simple Example: The t-test</h2>
<p>Suppose we want to evaluate the performance of a standard t-test for the hypothesis that the mean is equal to zero. We are interested to see how the size and power of the test change with the sample size (<em>n</em>), the distance from the null hypothesis (<em>loc</em> for location) and the standard deviation of the distribution (<em>scale</em>). The sample is generated from a normal distribution.</p>
<p>To conduct this analysis, we proceed as follows. First, we load the MonteCarlo package.</p>
<pre><code>library(MonteCarlo)
</code></pre>
<p>Then define the following function.</p>
<pre><code>#########################################
##      Example: t-test

# Define function that generates data and applies the method of interest

ttest&lt;-function(n,loc,scale){

  # generate sample:
    sample&lt;-rnorm(n, loc, scale)

  # calculate test statistic:
    stat&lt;-sqrt(n)*mean(sample)/sd(sample)

  # get test decision:
    decision1.96

  # return result:
    return(list(&quot;decision&quot;=decision))
}
</code></pre>
<p>As discussed above, <em>ttest()</em> is formulated in a way as if we only want to generate a single test decision. The arguments of the function are the parameters we are interested in. <em>ttest()</em> carries out 4 steps:</p>
<ol>
<li>Draw a sample of <em>n</em> observations from a normal distribution with mean <em>loc</em> and standard deviation <em>scale</em>.</li>
<li>Calculate the t-statistic.</li>
<li>Determine the test decision.</li>
<li>Return the desired result in form of a list.</li>
</ol>
<p>We then define the combinations of parameters that we are interested in and collect them in a list. The elements of the lists must have the same names as the parameters for which we want to supply grids.</p>
<pre><code># define parameter grid:

  n_grid&lt;-c(50,100,250,500)
  loc_grid&lt;-seq(0,1,0.2)
  scale_grid&lt;-c(1,2)

# collect parameter grids in list:
  param_list=list(&quot;n&quot;=n_grid, &quot;loc&quot;=loc_grid, &quot;scale&quot;=scale_grid)
</code></pre>
<p>To run the simulation, the function <em>ttest()</em> and the parameter grid (<em>param_list</em>) are passed to <em>MonteCarlo()</em>, together with the desired number of Monte Carlo repetitions (<em>nrep=1000</em>).</p>
<pre><code># run simulation:

  MC_result&lt;-MonteCarlo(func=ttest, nrep=1000, param_list=param_list)
</code></pre>
<p>There is no further coding required. All the mechanics of the Monte Carlo experiment are handled by the <em>MonteCarlo()</em> function.</p>
<p>Calling summary produces a short information on the simulation.</p>
<pre><code>  summary(MC_result)
</code></pre>
<pre><code>## Simulation of function: 
## 
## function(n,loc,scale){
##   
##   # generate sample:
##     sample&lt;-rnorm(n, loc, scale)
##   
##   # calculate test statistic:
##     stat&lt;-sqrt(n)*mean(sample)/sd(sample)
##   
##   # get test decision:
##     decision1.96
##   
##   # return result:
##     return(list(&quot;decision&quot;=decision))
## }
## 
## Required time: 13.38 secs for nrep = 1000  repetitions on 1 CPUs 
## 
## Parameter grid: 
## 
##      n : 50 100 250 500 
##    loc : 0 0.2 0.4 0.6 0.8 1 
##  scale : 1 2 
## 
##  
## 1 output arrays of dimensions: 4 6 2 1000
</code></pre>
<p>As one can see from the summary, the simulation results are stored in an array of dimension <code>c(4,6,2,1000)</code>, where the Monte Carlo repetitions are collected in the last dimension of the array.</p>
<p>To summarize the results in a reasonable way and to include them as a table in a paper or report, we have to represent them in a matrix. This is handled by the <em>MakeTable()</em> function that stacks the submatrices collected in the array in the rows and columns of a matrix and prints the result in the form of code to generate a LaTeX table.</p>
<p>To determine in which order the results are stacked in rows and columns, we supply the function arguments <em>rows</em> and <em>cols</em>. These are vectors of the names of the parameters in the order in which we want them to appear in the table (sorted from the inside to the outside).</p>
<pre><code># generate table:

  MakeTable(output=MC_result, rows=&quot;n&quot;, cols=c(&quot;loc&quot;,&quot;scale&quot;), digits=2, include_meta=FALSE)
</code></pre>
<pre><code>## \begin{table}[h]
## \centering
## \resizebox{ 1 \textwidth}{!}{%
## \begin{tabular}{ rrrrrrrrrrrrrrr }
## \hline\hline\\\\
##  scale &amp;&amp; \multicolumn{ 6 }{c}{ 1 } &amp;  &amp; \multicolumn{ 6 }{c}{ 2 } \\ 
## n/loc &amp;  &amp; 0 &amp; 0.2 &amp; 0.4 &amp; 0.6 &amp; 0.8 &amp; 1 &amp;  &amp; 0 &amp; 0.2 &amp; 0.4 &amp; 0.6 &amp; 0.8 &amp; 1 \\ 
##  &amp;  &amp;  &amp;  &amp;  &amp;  &amp;  &amp;  &amp;  &amp;  &amp;  &amp;  &amp;  &amp;  &amp;  \\ 
## 50 &amp;  &amp; 0.05 &amp; 0.30 &amp; 0.83 &amp; 0.98 &amp; 1.00 &amp; 1.00 &amp;  &amp; 0.05 &amp; 0.10 &amp; 0.28 &amp; 0.55 &amp; 0.79 &amp; 0.94 \\ 
## 100 &amp;  &amp; 0.05 &amp; 0.51 &amp; 0.98 &amp; 1.00 &amp; 1.00 &amp; 1.00 &amp;  &amp; 0.07 &amp; 0.16 &amp; 0.53 &amp; 0.84 &amp; 0.98 &amp; 1.00 \\ 
## 250 &amp;  &amp; 0.05 &amp; 0.89 &amp; 1.00 &amp; 1.00 &amp; 1.00 &amp; 1.00 &amp;  &amp; 0.05 &amp; 0.35 &amp; 0.90 &amp; 1.00 &amp; 1.00 &amp; 1.00 \\ 
## 500 &amp;  &amp; 0.05 &amp; 1.00 &amp; 1.00 &amp; 1.00 &amp; 1.00 &amp; 1.00 &amp;  &amp; 0.06 &amp; 0.58 &amp; 1.00 &amp; 1.00 &amp; 1.00 &amp; 1.00 \\ 
## \\
## \\
## \hline\hline
## \end{tabular}%
## }
## \caption{ decision  }
## \end{table}
</code></pre>
<p>To change the ordering, just change the vectors <em>rows</em> and <em>cols</em>.</p>
<pre><code># generate table:

  MakeTable(output=MC_result, rows=c(&quot;n&quot;,&quot;scale&quot;), cols=&quot;loc&quot;, digits=2, include_meta=FALSE)
</code></pre>
<pre><code>## \begin{table}[h]
## \centering
## \resizebox{ 1 \textwidth}{!}{%
## \begin{tabular}{ rrrrrrrrr }
## \hline\hline\\\\
## scale &amp; n/loc &amp;  &amp; 0 &amp; 0.2 &amp; 0.4 &amp; 0.6 &amp; 0.8 &amp; 1 \\ 
##  &amp;  &amp;  &amp;  &amp;  &amp;  &amp;  &amp;  &amp;  \\ 
## \multirow{ 4 }{*}{ 1 } &amp; 50 &amp;  &amp; 0.05 &amp; 0.30 &amp; 0.83 &amp; 0.98 &amp; 1.00 &amp; 1.00 \\ 
##  &amp; 100 &amp;  &amp; 0.05 &amp; 0.51 &amp; 0.98 &amp; 1.00 &amp; 1.00 &amp; 1.00 \\ 
##  &amp; 250 &amp;  &amp; 0.05 &amp; 0.89 &amp; 1.00 &amp; 1.00 &amp; 1.00 &amp; 1.00 \\ 
##  &amp; 500 &amp;  &amp; 0.05 &amp; 1.00 &amp; 1.00 &amp; 1.00 &amp; 1.00 &amp; 1.00 \\ 
##  &amp;  &amp;  &amp;  &amp;  &amp;  &amp;  &amp;  &amp;  \\ 
## \multirow{ 4 }{*}{ 2 } &amp; 50 &amp;  &amp; 0.05 &amp; 0.10 &amp; 0.28 &amp; 0.55 &amp; 0.79 &amp; 0.94 \\ 
##  &amp; 100 &amp;  &amp; 0.07 &amp; 0.16 &amp; 0.53 &amp; 0.84 &amp; 0.98 &amp; 1.00 \\ 
##  &amp; 250 &amp;  &amp; 0.05 &amp; 0.35 &amp; 0.90 &amp; 1.00 &amp; 1.00 &amp; 1.00 \\ 
##  &amp; 500 &amp;  &amp; 0.06 &amp; 0.58 &amp; 1.00 &amp; 1.00 &amp; 1.00 &amp; 1.00 \\ 
## \\
## \\
## \hline\hline
## \end{tabular}%
## }
## \caption{ decision  }
## \end{table}
</code></pre>
<p>Now we can simply copy the code and add it to our paper, report or presentation. That is all. Only make sure that the package <em>multirow</em> is included in the header of the <em>.tex</em> file.</p>
<h2>Parallelised Simulation</h2>
<p>If the procedure you are interested in is not so fast or you need a large number of replications to produce very accurate results, you might want to use parallelized computation on multiple cores of your computer (or cluster). To achive this, simply specify the number of CPUs by supplying a value for the argument <em>ncpus</em> of <em>MonteCarlo</em> as shown below. Of course you should actually have at least the specified number of units.</p>
<pre><code># run simulation:

  MC_result&lt;-MonteCarlo(func=ttest, nrep=1000, param_list=param_list, ncpus=4)
</code></pre>
<p>This automatically sets up a <em>snow</em> cluster, including the export of functions and the loading of packages. The user does not have to take care of anything.</p>
<h2>Further Information</h2>
<p>This is an introduction to get you up and running with the <em>MonteCarlo</em> package as quickly as possible. Therefore, I only included a short example. However, the functions <em>MonteCarlo()</em> and particularly <em>MakeTable()</em> provide much more functionality. This is described in more detail in the package <a rel="nofollow" href="https://cran.r-project.org/web/packages/MonteCarlo/vignettes/MonteCarlo-Vignette.html" target="_blank">vignette</a>, that also provides additional examples.</p>
<p>Filed under: <a rel="nofollow" href="https://firstdifferences.wordpress.com/category/r/" target="_blank">R</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/firstdifferences.wordpress.com/68/" target="_blank"><img border="0" alt="" src="http://feeds.wordpress.com/1.0/comments/firstdifferences.wordpress.com/68/"></a> <img border="0" alt="" src="https://i1.wp.com/pixel.wp.com/b.gif?resize=1%2C1&ssl=1" data-recalc-dims="1"></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/2017/06/08/introducing-the-montecarlo-package/"> 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 width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/YIA-DCt0zlA" height="1"></a></div>