<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/it-can-be-easy-to-explore-data-generating-mechanisms-with-the-simstudy-package/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://r-posts.com/it-can-be-easy-to-explore-data-generating-mechanisms-with-the-simstudy-package/"> R-posts.com</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p><img sizes="(max-width: 660px) 100vw, 660px" data-image-description="" data-orig-file="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/05/Plot-1.png?fit=700%2C500" data-orig-size="700,500" data-image-title="Plot 1" data-comments-opened="1" class="wp-image-144" data-recalc-dims="1" data-attachment-id="144" data-permalink="http://r-posts.com/it-can-be-easy-to-explore-data-generating-mechanisms-with-the-simstudy-package/plot-1/" alt="" data-medium-file="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/05/Plot-1.png?fit=420%2C300" data-large-file="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/05/Plot-1.png?fit=450%2C321" data-image-meta="{" src="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/05/Plot-1.png?resize=660%2C471"></p>
<p>I learned statistics and probability by simulating data. Sure, I battled my way through proofs, but I never believed the results until I saw it in a simulation. I guess I have it backwards, it worked for me. And now that I do this for a living, I continue to use simulation to understand models, to do sample size estimates and power calculations, and of course to teach. Sure – I’ll use the occasional formula, but I always feel the need to check it with simulation. It’s just the way I am. </p>
<p>Since I found myself constantly setting up simulations, over time I developed ways to make the process a bit easier. Those processes turned into a package, which I called <a target="_blank" rel="nofollow" href="https://cran.r-project.org/web/packages/simstudy/index.html">simstudy</a>, or <em>simulating study data</em>. My goal here is to introduce the basic idea behind simstudy, and provide a relatively simple example that comes from a question posed by a user who was trying to generate correlated longitudinal data.</p>
<h2>The basic idea</h2>
<p>Simulation using simstudy has two essential steps. First, the user defines the data elements of a data set either in an external csv file or internally through a set of repeated definition statements. Second, the user generates the data, using these definitions. Data generation can be as simple as a cross-sectional design or prospective cohort design, or it can be more involved. Simulation can include observed or randomized <em>treatment assignment/exposures</em>, <em>survival</em> data, <em>longitudinal/panel</em> data, <em>multi-level/hierarchical</em> data, data sets with <em>correlated variables</em> based on a specified covariance structure, and data sets with <em>missing</em> data resulting from any sort of missingness pattern.</p>
<p>The key to simulating data in simstudy is the creation of series of data definition tables that look like this:</p>
<p><img sizes="(max-width: 660px) 100vw, 660px" data-image-description="" data-orig-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/05/test-e1494624690930.png?fit=1568%2C932" data-orig-size="1568,932" data-image-title="test" data-comments-opened="1" class="wp-image-138" data-recalc-dims="1" data-attachment-id="138" data-permalink="http://r-posts.com/it-can-be-easy-to-explore-data-generating-mechanisms-with-the-simstudy-package/test/" alt="" data-medium-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/05/test-e1494624690930.png?fit=450%2C267" data-large-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/05/test-e1494624690930.png?fit=450%2C267" data-image-meta="{" src="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/05/test-e1494624690930.png?resize=660%2C392"></p>
<p>Here’s the code that is used to generate this definition, which is stored as a <a target="_blank" rel="nofollow" href="https://github.com/Rdatatable/data.table/wiki">data.table </a>:</p>
<pre><pre>
def &lt;- defData(varname = &quot;nr&quot;, dist = &quot;nonrandom&quot;, formula = 7, id = &quot;idnum&quot;)
def &lt;- defData(def, varname = &quot;x1&quot;, dist = &quot;uniform&quot;, formula = &quot;10;20&quot;)
def &lt;- defData(def, varname = &quot;y1&quot;, formula = &quot;nr + x1 * 2&quot;, variance = 8)
def &lt;- defData(def, varname = &quot;y2&quot;, dist = &quot;poisson&quot;, formula = &quot;nr - 0.2 * x1&quot;, link = &quot;log&quot;)
def &lt;- defData(def, varname = &quot;xCat&quot;, formula = &quot;0.3;0.2;0.5&quot;, dist = &quot;categorical&quot;)
def &lt;- defData(def, varname = &quot;g1&quot;, dist = &quot;gamma&quot;, formula = &quot;5+xCat&quot;, variance = 1, link = &quot;log&quot;)
def &lt;- defData(def, varname = &quot;a1&quot;, dist = &quot;binary&quot;, formula = &quot;-3 + xCat&quot;, link = &quot;logit&quot;)
</pre>
<p>To create a simple data set based on these definitions, all one needs to do is execute a single <code>genData</code> command. In this example, we generate 500 records that are based on the definition in the <code>def</code> table:</p>
<pre><pre>
dt &lt;- genData(500, def)

dt
</pre>
<pre>
##      idnum nr       x1       y1  y2 xCat          g1 a1
##   1:     1  7 10.74929 30.01273 123    3 13310.84731  0
##   2:     2  7 18.56196 44.77329  17    1   395.41606  0
##   3:     3  7 16.96044 43.76427  42    3   522.45258  0
##   4:     4  7 19.51511 45.14214  22    3  3045.06826  0
##   5:     5  7 10.79791 27.25012 128    1   406.88647  0
##  ---                                                   
## 496:   496  7 19.96636 52.05377  21    3   264.85557  1
## 497:   497  7 15.97957 39.62428  44    2    40.59823  0
## 498:   498  7 19.74036 47.32292  21    3  3410.54787  0
## 499:   499  7 19.71597 48.26259  25    3   206.90961  1
## 500:   500  7 14.60405 28.94185  53    1    97.43068  0
</pre>
<p>There’s a lot more functionality in the package, and I’ll be writing about that in the future. But here, I just want give a little more introduction by way of an example that came in from across the globe a couple of days ago. (I’d say the best thing about building an R package is hearing from folks literally all over the world and getting to talk to them about statistics and R.)</p>
<h2>Going a bit further: simulating a prospective cohort study with repeated measures</h2>
<p>The question was, can we simulate a study with two arms, say a control and treatment, with repeated measures at three time points: baseline, after 1 month, and after 2 months? The answer is, of course.</p>
<p>Drawing on her original code, we wanted a scenario the included two treatment arms or exposures and three measurements per individual. The change over time was supposed to be greater for one of the groups. This was what I sent back to my correspondent:</p>
<pre><pre>
# Define the outcome

ydef &lt;- defDataAdd(varname = &quot;Y&quot;, dist = &quot;normal&quot;, 
                   formula = &quot;5 + 2.5*period + 1.5*T + 3.5*period*T&quot;, 
                   variance = 3)

# Generate a 'blank' data.table with 24 observations and assign them to groups

set.seed(1234)

indData &lt;- genData(24)
indData &lt;- trtAssign(indData, nTrt = 2, balanced = TRUE, grpName = &quot;T&quot;)

# Create a longitudinal data set of 3 records for each id

longData &lt;- addPeriods(indData, nPeriods = 3, idvars = &quot;id&quot;)
longData &lt;- addColumns(dtDefs = ydef, longData)

longData[, `:=`(T, factor(T, labels = c(&quot;No&quot;, &quot;Yes&quot;)))]

# Let's look at the data

ggplot(data = longData, aes(x = factor(period), y = Y)) + geom_line(aes(color = T, 
    group = id)) + scale_color_manual(values = c(&quot;#e38e17&quot;, &quot;#8e17e3&quot;)) + xlab(&quot;Time&quot;)
</pre>
<p><img sizes="(max-width: 660px) 100vw, 660px" data-image-description="" data-orig-file="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/05/Plot-1.png?fit=700%2C500" data-orig-size="700,500" data-image-title="Plot 1" data-comments-opened="1" class="wp-image-144" data-recalc-dims="1" data-attachment-id="144" data-permalink="http://r-posts.com/it-can-be-easy-to-explore-data-generating-mechanisms-with-the-simstudy-package/plot-1/" alt="" data-medium-file="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/05/Plot-1.png?fit=420%2C300" data-large-file="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/05/Plot-1.png?fit=450%2C321" data-image-meta="{" src="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/05/Plot-1.png?resize=660%2C471"></p>
<p>My correspondent quickly pointed out that I hadn’t really provided her with the full solution – as the measurements for each individual in the example above are not correlated across the time periods. If we generate a data set based on 1,000 individuals and estimate a linear regression model we see that the parameter estimates are quite good, though we can see from the estimate of alpha (at the bottom of the output), which was approximately 0.02, that there is little within-individual correlation:</p>
<pre><pre>
# Fit a GEE model to the data

fit &lt;- geeglm(Y ~ factor(T) + period + factor(T) * period, family = gaussian(link = &quot;identity&quot;), 
    data = longData, id = id, corstr = &quot;exchangeable&quot;)
summary(fit)</pre>
<pre><pre>## 
## Call:
## geeglm(formula = Y ~ factor(T) + period + factor(T) * period, 
##     family = gaussian(link = &quot;identity&quot;), data = longData, id = id, 
##     corstr = &quot;exchangeable&quot;)
## 
##  Coefficients:
##                     Estimate Std.err   Wald Pr(>|W|)    
## (Intercept)          4.98268 0.07227 4753.4   &lt;2e-16 ***
## factor(T)Yes         1.48555 0.10059  218.1   &lt;2e-16 ***
## period               2.53946 0.05257 2333.7   &lt;2e-16 ***
## factor(T)Yes:period  3.51294 0.07673 2096.2   &lt;2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Estimated Scale Parameters:
##             Estimate Std.err
## (Intercept)    2.952 0.07325
## 
## Correlation: Structure = exchangeable  Link = identity 
## 
## Estimated Correlation Parameters:
##       Estimate Std.err
## alpha  0.01737 0.01862
## Number of clusters:   1000   Maximum cluster size: 3
</pre>
<h2>One way to generate correlated data</h2>
<p>To address this shortcoming, there are at least two ways we can go about it. The first is to use the simstudy function <code>genCorData</code>. In this example, we generate correlated errors that are normally distributed with mean 0, variance 3, and common correlation coefficient of 0.7. Using this approach, the underlying data generation process is a bit cryptic, because we are acknowledging that we don’t know what is driving the relationship between the three outcomes, just that they have some common cause or other relationship that results in a strong relationship. However, it does the trick:</p>
<pre><pre>
# define the outcome
ydef &lt;- defDataAdd(varname = &quot;Y&quot;, dist = &quot;normal&quot;, formula = &quot;5 + 2.5*period + 1.5*T + 3.5*period*T + e&quot;)

# define the correlated errors

mu &lt;- c(0, 0, 0)
sigma &lt;- rep(sqrt(3), 3)

# generate correlated data for each id and assign treatment

dtCor &lt;- genCorData(24, mu = mu, sigma = sigma, rho = 0.7, corstr = &quot;cs&quot;)
dtCor &lt;- trtAssign(dtCor, nTrt = 2, balanced = TRUE, grpName = &quot;T&quot;)

# create longitudinal data set and generate outcome based on definition

longData &lt;- addPeriods(dtCor, nPeriods = 3, idvars = &quot;id&quot;, timevars = c(&quot;V1&quot;, 
    &quot;V2&quot;, &quot;V3&quot;), timevarName = &quot;e&quot;)
longData &lt;- addColumns(ydef, longData)

longData[, `:=`(T, factor(T, labels = c(&quot;No&quot;, &quot;Yes&quot;)))]

# look at the data, outcomes should appear more correlated, lines a bit straighter

ggplot(data = longData, aes(x = factor(period), y = Y)) + geom_line(aes(color = T, 
    group = id)) + scale_color_manual(values = c(&quot;#e38e17&quot;, &quot;#8e17e3&quot;)) + xlab(&quot;Time&quot;)
</pre>
<p><img sizes="(max-width: 660px) 100vw, 660px" data-image-description="" data-orig-file="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/05/Plot-2.png?fit=700%2C500" data-orig-size="700,500" data-image-title="Plot 2" data-comments-opened="1" class="wp-image-145" data-recalc-dims="1" data-attachment-id="145" data-permalink="http://r-posts.com/it-can-be-easy-to-explore-data-generating-mechanisms-with-the-simstudy-package/plot-2/" alt="" data-medium-file="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/05/Plot-2.png?fit=420%2C300" data-large-file="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/05/Plot-2.png?fit=450%2C321" data-image-meta="{" src="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/05/Plot-2.png?resize=660%2C471"></p>
<p>Again, we recover the true parameters. And this time, if we look at the estimated correlation, we see that indeed the outcomes are correlated within each individual. The estimate is 0.71, very close to the the “true” value 0.7.</p>
<pre><pre>
fit &lt;- geeglm(Y ~ factor(T) + period + factor(T) * period, family = gaussian(link = &quot;identity&quot;), 
    data = longData, id = id, corstr = &quot;exchangeable&quot;)

summary(fit)</pre>
<pre><pre>
## 
## Call:
## geeglm(formula = Y ~ factor(T) + period + factor(T) * period, 
##     family = gaussian(link = &quot;identity&quot;), data = longData, id = id, 
##     corstr = &quot;exchangeable&quot;)
## 
##  Coefficients:
##                     Estimate Std.err Wald Pr(>|W|)    
## (Intercept)           5.0636  0.0762 4411   &lt;2e-16 ***
## factor(T)Yes          1.4945  0.1077  192   &lt;2e-16 ***
## period                2.4972  0.0303 6798   &lt;2e-16 ***
## factor(T)Yes:period   3.5204  0.0426 6831   &lt;2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Estimated Scale Parameters:
##             Estimate Std.err
## (Intercept)     3.07   0.117
## 
## Correlation: Structure = exchangeable  Link = identity 
## 
## Estimated Correlation Parameters:
##       Estimate Std.err
## alpha    0.711  0.0134
## Number of clusters:   1000   Maximum cluster size: 3
</pre>
<h2>Another way to generate correlated data</h2>
<p>A second way to generate correlated data is through an individual level random-effect or random intercept. This could be considered some unmeasured characteristic of the individuals (which happens to have a convenient normal distribution with mean zero). This random effect contributes equally to all instances of an individuals outcomes, but the outcomes for a particular individual deviate slightly from the hypothetical straight line as a result of unmeasured noise.</p>
<pre><pre>
ydef1 &lt;- defData(varname = &quot;randomEffect&quot;, dist = &quot;normal&quot;, formula = 0, variance = sqrt(3))
ydef2 &lt;- defDataAdd(varname = &quot;Y&quot;, dist = &quot;normal&quot;, formula = &quot;5 + 2.5*period + 1.5*T + 3.5*period*T + randomEffect&quot;, 
    variance = 1)

indData &lt;- genData(24, ydef1)
indData &lt;- trtAssign(indData, nTrt = 2, balanced = TRUE, grpName = &quot;T&quot;)

indData[1:6]</pre>
<pre><pre>##    id T randomEffect
## 1:  1 0      -1.3101
## 2:  2 1       0.3423
## 3:  3 0       0.5716
## 4:  4 1       2.6723
## 5:  5 0      -0.9996
## 6:  6 1      -0.0722
</pre>
<pre><pre>
longData &lt;- addPeriods(indData, nPeriods = 3, idvars = &quot;id&quot;)
longData &lt;- addColumns(dtDefs = ydef2, longData)

longData[, `:=`(T, factor(T, labels = c(&quot;No&quot;, &quot;Yes&quot;)))]

ggplot(data = longData, aes(x = factor(period), y = Y)) + geom_line(aes(color = T, 
    group = id)) + scale_color_manual(values = c(&quot;#e38e17&quot;, &quot;#8e17e3&quot;)) + xlab(&quot;Time&quot;)
</pre>
<p><img sizes="(max-width: 660px) 100vw, 660px" data-image-description="" data-orig-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/05/Plot-3.png?fit=700%2C500" data-orig-size="700,500" data-image-title="Plot 3" data-comments-opened="1" class="wp-image-146" data-recalc-dims="1" data-attachment-id="146" data-permalink="http://r-posts.com/it-can-be-easy-to-explore-data-generating-mechanisms-with-the-simstudy-package/plot-3/" alt="" data-medium-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/05/Plot-3.png?fit=420%2C300" data-large-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/05/Plot-3.png?fit=450%2C321" data-image-meta="{" src="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/05/Plot-3.png?resize=660%2C471"></p>
<pre><pre>
fit &lt;- geeglm(Y ~ factor(T) + period + factor(T) * period, family = gaussian(link = &quot;identity&quot;), 
    data = longData, id = id, corstr = &quot;exchangeable&quot;)
summary(fit)</pre>
<pre><pre>
## 
## Call:
## geeglm(formula = Y ~ factor(T) + period + factor(T) * period, 
##     family = gaussian(link = &quot;identity&quot;), data = longData, id = id, 
##     corstr = &quot;exchangeable&quot;)
## 
##  Coefficients:
##                     Estimate Std.err Wald Pr(>|W|)    
## (Intercept)           4.9230  0.0694 5028   &lt;2e-16 ***
## factor(T)Yes          1.4848  0.1003  219   &lt;2e-16 ***
## period                2.5310  0.0307 6793   &lt;2e-16 ***
## factor(T)Yes:period   3.5076  0.0449 6104   &lt;2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Estimated Scale Parameters:
##             Estimate Std.err
## (Intercept)     2.63  0.0848
## 
## Correlation: Structure = exchangeable  Link = identity 
## 
## Estimated Correlation Parameters:
##       Estimate Std.err
## alpha    0.619  0.0146
## Number of clusters:   1000   Maximum cluster size: 3
</pre>
<p>I sent all this back to my correspondent, but I haven’t heard yet if either of these solutions meets her needs. I certainly hope so. Speaking of which, if there are specific topics you’d like me to discuss related to simstudy, definitely get in touch, and I will try to write something up.</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://r-posts.com/it-can-be-easy-to-explore-data-generating-mechanisms-with-the-simstudy-package/"> R-posts.com</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 title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/AzSIGX5XDIM"></a></div></pre></pre></pre></pre></pre></pre></pre></pre></pre></pre></pre></pre></pre>