<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/linear-mixed-effect-models-in-r/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://poissonisfish.wordpress.com/2017/12/11/linear-mixed-effect-models-in-r/"> poissonisfish</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<figure data-shortcode="caption" class="wp-caption"><img data-orig-file="https://poissonisfish.files.wordpress.com/2017/05/arabidopsis_thaliana_rosette_transparent_background.png?w=247&amp;h=240&amp;fit=247%2C240&amp;resize=247%2C240" data-orig-size="2172,2110" data-medium-file="https://poissonisfish.files.wordpress.com/2017/05/arabidopsis_thaliana_rosette_transparent_background.png?w=247&amp;h=240&amp;fit=247%2C240&amp;resize=247%2C240?w=300" data-attachment-id="2379" data-image-meta="{" data-image-description="" src="https://poissonisfish.files.wordpress.com/2017/05/arabidopsis_thaliana_rosette_transparent_background.png?w=247&h=240&fit=247%2C240&resize=247%2C240" data-permalink="https://poissonisfish.wordpress.com/2017/12/11/linear-mixed-effect-models-in-r/arabidopsis_thaliana_rosette_transparent_background/" data-large-file="https://poissonisfish.files.wordpress.com/2017/05/arabidopsis_thaliana_rosette_transparent_background.png?w=247&amp;h=240&amp;fit=247%2C240&amp;resize=247%2C240?w=1024" alt="Arabidopsis_thaliana_rosette_transparent_background" data-image-title="Arabidopsis_thaliana_rosette_transparent_background" sizes="(max-width: 247px) 100vw, 247px" data-comments-opened="1" class="wp-image-2379" data-recalc-dims="1"><figcaption class="wp-caption-text"><em>Arabidopsis thaliana</em> rosette. From: Wikimedia Commons</figcaption></figure>
<p>Statistical models generally assume that</p>
<ol>
<li>All observations are independent from each other</li>
<li>The distribution of the residuals follows <img alt="mathcal{N}(0, sigma^2)" title="mathcal{N}(0, sigma^2)" src="https://s0.wp.com/latex.php?latex=%5Cmathcal%7BN%7D%280%2C+%5Csigma%5E2%29&bg=f9f9f9&%23038;fg=555555&%23038;s=1" class="latex">, irrespective of the values taken by the dependent variable <em>y</em></li>
</ol>
<p>When any of the two is not observed, more sophisticated modelling approaches are necessary. Let’s consider two hypothetical problems that violate the two respective assumptions, where <em>y</em> denotes the dependent variable:</p>
<p><strong>A.</strong> Suppose you want to study the relationship between average income (<em>y</em>) and the educational level in the population of a town comprising four fully segregated blocks. You will sample 1,000 individuals irrespective of their blocks. If you model as such, you neglect dependencies among observations – individuals from the same block are not independent, yielding residuals that correlate within block.</p>
<p><strong>B.</strong> Suppose you want to study the relationship between anxiety (<em>y</em>) and the levels of triglycerides and uric acid in blood samples from 1,000 people, measured 10 times in the course of 24 hours. If you model as such, you will likely find that the variance of <em>y </em>changes over time – this is an example of <a rel="nofollow" href="https://en.wikipedia.org/wiki/Heteroscedasticity" target="_blank">heteroscedasticity</a>, a phenomenon characterized by the heterogeneity in the variance of the residuals.</p>
<p>In <strong>A.</strong> we have a problem of dependency caused by spatial correlation, whereas in <strong>B.</strong> we have a problem of heterogeneous variance. As a result, classic linear models cannot help in these hypothetical problems, but both can be addressed using linear mixed-effect models (LMMs). In rigour though, you do not need LMMs to address the second problem.</p>
<p>LMMs are extraordinarily powerful, yet their complexity undermines the appreciation from a broader community. LMMs dissect hierarchical and / or longitudinal (<em>i.e.</em> time course) data by separating the variance due to random sampling from the main effects. In essence, on top of the fixed effects normally used in classic linear models, LMMs resolve <em>i</em>) correlated residuals by introducing random effects that account for differences among random samples, and <em>ii</em>) heterogeneous variance using specific variance functions, thereby improving the estimation accuracy and interpretation of fixed effects in one go.</p>
<p>I personally reckon that most relevant textbooks and papers are hard to grasp for non-mathematicians. Therefore, following the brief reference in my last post on GWAS I will dedicate the present tutorial to LMMs. For further reading I highly recommend the ecology-oriented <a rel="nofollow" href="http://www.springer.com/gb/book/9780387874579" target="_blank">Zuur <em>et al</em>. (2009)</a> and the R-intensive <a rel="nofollow" href="http://www.springer.com/gb/book/9781461438991" target="_blank">Gałecki <em>et al</em>. (2013)</a> books, and <a rel="nofollow" href="http://www.bodowinter.com/tutorial/bw_LME_tutorial2.pdf" target="_blank">this simple tutorial</a> from Bodo Winter. For agronomic applications, <a rel="nofollow" href="http://onlinelibrary.wiley.com/doi/10.1046/j.1439-037X.2003.00049.x/abstract" target="_blank">H.-P. Piepho <em>et al</em>. (2003)</a> is an excellent theoretical introduction.</p>
<p>Here, we will build LMMs using the Arabidopsis dataset from the package <code>lme4</code>, from a study published by <a rel="nofollow" href="http://onlinelibrary.wiley.com/doi/10.1111/j.1600-0706.2009.17726.x/abstract" target="_blank">Banta <em>et al</em>. (2010)</a>. These data summarize variation in total fruit set per plant in <em>Arabidopsis thaliana</em> plants conditioned to fertilization and simulated herbivory. Our goal is to understand the effect of fertilization and simulated herbivory adjusted to experimental differences across groups of plants.</p>
<h2>Mixed-effect linear models</h2>
<p>Whereas the classic linear model with <em>n</em> observational units and <em>p</em> predictors has the vectorized form</p>
<p><img alt="mathbf{y} = mathbf{X}beta + epsilon " title="mathbf{y} = mathbf{X}beta + epsilon " src="https://s0.wp.com/latex.php?latex=%5Cmathbf%7By%7D+%3D+%5Cmathbf%7BX%7D%5Cbeta+%2B+%5Cepsilon+&bg=f9f9f9&%23038;fg=555555&%23038;s=2" class="latex"></p>
<p>with the <img alt="n times (p+1) " title="n times (p+1) " src="https://s0.wp.com/latex.php?latex=n+%5Ctimes+%28p%2B1%29+&bg=f9f9f9&%23038;fg=555555&%23038;s=1" class="latex"> predictor matrix <img alt="mathbf{X} " title="mathbf{X} " src="https://s0.wp.com/latex.php?latex=%5Cmathbf%7BX%7D+&bg=f9f9f9&%23038;fg=555555&%23038;s=1" class="latex">, the vector of <i>p</i> + 1 coefficient estimates <img alt="beta " title="beta " src="https://s0.wp.com/latex.php?latex=%5Cbeta+&bg=f9f9f9&%23038;fg=555555&%23038;s=1" class="latex"> and the <em>n</em>-long vectors of the response <img alt="mathbf{y} " title="mathbf{y} " src="https://s0.wp.com/latex.php?latex=%5Cmathbf%7By%7D+&bg=f9f9f9&%23038;fg=555555&%23038;s=1" class="latex"> and the residuals <img alt="epsilon " title="epsilon " src="https://s0.wp.com/latex.php?latex=%5Cepsilon+&bg=f9f9f9&%23038;fg=555555&%23038;s=1" class="latex">, LMMs additionally accomodate separate variance components modelled with a set of random effects <img alt="mathbf{u} " title="mathbf{u} " src="https://s0.wp.com/latex.php?latex=%5Cmathbf%7Bu%7D+&bg=f9f9f9&%23038;fg=555555&%23038;s=1" class="latex">,</p>
<p><img alt="mathbf{y} = mathbf{X}beta + mathbf{Z}mathbf{u} + epsilon " title="mathbf{y} = mathbf{X}beta + mathbf{Z}mathbf{u} + epsilon " src="https://s0.wp.com/latex.php?latex=%5Cmathbf%7By%7D+%3D+%5Cmathbf%7BX%7D%5Cbeta+%2B+%5Cmathbf%7BZ%7D%5Cmathbf%7Bu%7D+%2B+%5Cepsilon+&bg=f9f9f9&%23038;fg=555555&%23038;s=2" class="latex"></p>
<p>where <img alt="mathbf{Z} " title="mathbf{Z} " src="https://s0.wp.com/latex.php?latex=%5Cmathbf%7BZ%7D+&bg=f9f9f9&%23038;fg=555555&%23038;s=1" class="latex"> and <img alt="mathbf{X} " title="mathbf{X} " src="https://s0.wp.com/latex.php?latex=%5Cmathbf%7BX%7D+&bg=f9f9f9&%23038;fg=555555&%23038;s=1" class="latex"> are design matrices that jointly represent the set of predictors. Random effects models include only an intercept as the fixed effect and a defined set of random effects. Random effects comprise random intercepts and / or random slopes. Also, random effects might be crossed and nested. In terms of estimation, the classic linear model can be easily solved using the least-squares method. For the LMM, however, we need methods that rather than estimating predict <img alt="mathbf{u} " title="mathbf{u} " src="https://s0.wp.com/latex.php?latex=%5Cmathbf%7Bu%7D+&bg=f9f9f9&%23038;fg=555555&%23038;s=1" class="latex">, such as maximum likelihood (ML) and restricted maximum likelihood (REML). Bear in mind that unlike ML, REML assumes that the fixed effects are not known, hence it is comparatively unbiased (see Chapter 5 in <a rel="nofollow" href="http://www.springer.com/gb/book/9780387874579" target="_blank">Zuur <em>et al</em>. (2009)</a> for more details). Unfortunately, LMMs too have underlying assumptions – <strong>both residuals and random effects should be normally distributed</strong>. Residuals in particular should also have a uniform variance over different values of the dependent variable, exactly as assumed in a classic linear model.</p>
<p>One of the most common doubts concerning LMMs is determining whether a variable is a random or fixed. First of all, an effect might be fixed, random or even both simultaneously – it largely depends on how you approach a given problem. Generally, you should consider all factors that qualify as sampling from a population as random effects (<em>e.g.</em> individuals in repeated measurements, cities within countries, field trials, plots, blocks, batches) and everything else as fixed. As a rule of thumb, <em>i</em>) factors with fewer than 5 levels should be considered fixed and conversely <em>ii</em>) factors with numerous levels should be considered random effects in order to increase the accuracy in the estimation of variance. Both points relate to the LMM assumption of having normally distributed random effects.</p>
<p>Best linear unbiased estimators (BLUEs) and predictors (BLUPs) correspond to the values of fixed and random effects, respectively. The usage of the so-called genomic BLUPs (GBLUPs), for instance, elucidates the genetic merit of animal or plant genotypes that are regarded as random effects when trial conditions, <em>e.g.</em> location and year of trials are considered fixed. However, many studies sought the opposite, <em>i.e.</em> using breeding values as fixed effects and trial conditions as random, when the levels of the latter outnumber the former, chiefly because of point <em>ii</em>) outlined above. In GWAS, LMMs aid in teasing out population structure from the phenotypic measures.</p>
<h1>Let’s get started with R</h1>
<p>We will follow a structure similar to the 10-step protocol outlined in <a rel="nofollow" href="http://www.springer.com/gb/book/9780387874579" target="_blank">Zuur <em>et al</em>. (2009)</a>: <em>i</em>) fit a full ordinary least squares model and run the diagnostics in order to understand if and what is faulty about its fit; <em>ii</em>) fit an identical generalized linear model (GLM) estimated with ML, to serve as a reference for subsequent LMMs; <em>iii</em>) deploy the first LMM by introducing random effects and compare to the GLM, optimize the random structure in subsequent LMMs; <em>iv</em>) optimize the fixed structure by determining the significant of fixed effects, always using ML estimation; finally, <em>v</em>) use REML estimation on the optimal model and interpret the results.</p>
<p>You need to have<code>nlme</code><strong> </strong>and<code>lme4</code><strong> </strong>installed to proceed. We will firstly examine the structure of the Arabidopsis dataset.</p>
<pre>
# Install (if necessary) and load nlme and lme4
library(nlme)
library(lme4)
# Load dataset, inspect size and additional info
data(Arabidopsis)
dim(Arabidopsis) # 625 observations, 8 variables
?Arabidopsis
attach(Arabidopsis)
</pre>
<p>The Arabidopsis dataset describes 625 plants with respect to the the following 8 variables (transcript from R):</p>
<dl>
<dt><code>reg</code></dt>
<dd>region: a factor with 3 levels <code>NL</code> (Netherlands), <code>SP</code> (Spain), <code>SW</code> (Sweden)
</dd>
<dt><code>popu</code></dt>
<dd>population: a factor with the form <code>n.R</code> representing a population in region <code>R</code>
</dd>
<dt><code>gen</code></dt>
<dd>genotype: a factor with 24 (numeric-valued) levels
</dd>
<dt><code>rack</code></dt>
<dd>a nuisance factor with 2 levels, one for each of two greenhouse racks
</dd>
<dt><code>nutrient</code></dt>
<dd>fertilization treatment/nutrient level (1, minimal nutrients or 8, added nutrients)
</dd>
<dt><code>amd</code></dt>
<dd>simulated herbivory or “clipping” (apical meristem damage): <code>unclipped</code>(baseline) or <code>clipped</code>
</dd>
<dt><code>status</code></dt>
<dd>a nuisance factor for germination method (<code>Normal</code>, <code>Petri.Plate</code>, or <code>Transplant</code>)
</dd>
<dt><code>total.fruits</code></dt>
<dd>total fruit set per plant (integer), henceforth TFPP for short.
</dd>
</dl>
<p>We will now visualise the absolute frequencies in all 7 factors and the distribution for TFPP.</p>
<pre>
# Overview of the variables
par(mfrow = c(2,4))
barplot(table(reg), ylab = &quot;Frequency&quot;, main = &quot;Region&quot;)
barplot(table(popu), ylab = &quot;Frequency&quot;, main = &quot;Population&quot;)
barplot(table(gen), ylab = &quot;Frequency&quot;, las = 2, main = &quot;Genotype&quot;)
barplot(table(rack), ylab = &quot;Frequency&quot;, main = &quot;Rack&quot;)
barplot(table(nutrient), ylab = &quot;Frequency&quot;, main = &quot;Nutrient&quot;)
barplot(table(amd), ylab = &quot;Frequency&quot;, main = &quot;AMD&quot;)
barplot(table(status), ylab = &quot;Frequency&quot;, main = &quot;Status&quot;)
hist(total.fruits, col = &quot;grey&quot;, main = &quot;Total fruits&quot;, xlab = NULL)
</pre>
<p><img data-orig-file="https://poissonisfish.files.wordpress.com/2017/12/plot1.png?w=456" data-orig-size="1039,459" data-medium-file="https://poissonisfish.files.wordpress.com/2017/12/plot1.png?w=456?w=300" data-attachment-id="4322" data-image-meta="{" data-image-description="" src="https://poissonisfish.files.wordpress.com/2017/12/plot1.png?w=456" data-permalink="https://poissonisfish.wordpress.com/2017/12/11/linear-mixed-effect-models-in-r/plot1/" data-large-file="https://poissonisfish.files.wordpress.com/2017/12/plot1.png?w=456?w=1024" alt="plot1" data-image-title="plot1" sizes="(max-width: 1039px) 100vw, 1039px" data-comments-opened="1" class="wp-image-4322" data-recalc-dims="1"></p>
<p>The frequencies are overall balanced, perhaps except for <code>status</code> (<em>i.e.</em> germination method). Genotype, greenhouse rack and fertilizer are incorrectly interpreted as quantitative variables. In addition, the distribution of TFPP is right-skewed. As such, we will encode these three variables as categorical variables and log-transform TFPP to approximate a Gaussian distribution (natural logarithm).</p>
<pre>
# Transform the three factor variables gen, rack and nutrient
Arabidopsis[,c(&quot;gen&quot;,&quot;rack&quot;,&quot;nutrient&quot;)] &lt;- lapply(Arabidopsis[,c(&quot;gen&quot;,&quot;rack&quot;,&quot;nutrient&quot;)], factor)
str(Arabidopsis)
# Re-attach after correction, ignore warnings
attach(Arabidopsis)
# Add 1 to total fruits, otherwise log of 0 will prompt error
total.fruits &lt;- log(1 + total.fruits)
</pre>
<p>A closer look into the variables shows that each genotype is exclusive to a single region. The data contain no missing values.</p>
<pre>
# gen x popu table
table(gen, popu)
# Any NAs?
any(is.na(Arabidopsis)) # FALSE
</pre>
<h2>Formula syntax basics</h2>
<p><span>At this point I hope you are familiar with the formula syntax in R. Note that interaction terms are denoted by <code>:</code></span><span> and fully crossed effects with <code>*</code></span><span>,</span><strong> </strong><span>so that </span><code>A*B = A + B + A:B</code>.<span> The following code example</span></p>
<pre>lm(y ~ x1 + x2*x3)
</pre>
<p>builds a linear model of <em>y </em>using <img alt="x_1 " title="x_1 " src="https://s0.wp.com/latex.php?latex=x_1+&bg=f9f9f9&%23038;fg=555555&%23038;s=1" class="latex">, <img alt="x_2 " title="x_2 " src="https://s0.wp.com/latex.php?latex=x_2+&bg=f9f9f9&%23038;fg=555555&%23038;s=1" class="latex">, <img alt="x_3 " title="x_3 " src="https://s0.wp.com/latex.php?latex=x_3+&bg=f9f9f9&%23038;fg=555555&%23038;s=1" class="latex"> and the interaction between <img alt="x_2 " title="x_2 " src="https://s0.wp.com/latex.php?latex=x_2+&bg=f9f9f9&%23038;fg=555555&%23038;s=1" class="latex"> and <img alt="x_3 " title="x_3 " src="https://s0.wp.com/latex.php?latex=x_3+&bg=f9f9f9&%23038;fg=555555&%23038;s=1" class="latex">. <span>In case you want to perform arithmetic operations inside the formula, use the function <code>I</code></span><span>. You can also introduce polynomial terms with the function <code>poly</code>. One handy trick I use to expand all pairwise interactions among predictors is</span></p>
<pre>model.matrix(y ~ .*., data = X)</pre>
<p>provided a matrix <em>X</em> that gathers all predictors and <em>y. </em>You can also simply use <code>.*.</code> inside the <code>lm</code> call, however you will likely need to preprocess the resulting interaction terms.</p>
<p><span>While the syntax of <code>lme</code></span><strong> </strong><span>is identical to <code>lm</code> for fixed effects, its random effects are specified under the argument</span><span><b> </b><code>random</code></span><span> as</span></p>
<pre>random = ~intercept + fixed effect | random effect</pre>
<p>and can be nested using <code>/</code>. In the following example</p>
<pre>random = ~1 + C | A/B</pre>
<p>the random effect B is nested within random effect A, altogether with random intercept and slope with respect to C. Therefore, not only will the groups defined by A and A/B have different intercepts, they will also be explained by different slight shifts of <img alt="beta " title="beta " src="https://s0.wp.com/latex.php?latex=%5Cbeta+&bg=f9f9f9&%23038;fg=555555&%23038;s=1" class="latex"> from the fixed effect C.</p>
<h2>Classic linear model</h2>
<p>Ideally, you should start will a full model (<em>i.e.</em> including all independent variables). Here, however, we cannot use all descriptors in the classic linear model since the fit will be singular due to the redundancy in the levels of <code>reg</code> and <code>popu</code>. For simplicity I will exclude these alongside <code>gen</code>, since it contains a lot of levels and also represents a random sample (from many other extant Arabidopsis genotypes). Additionally, I would rather use <code>rack</code> and <strong> </strong><code>status</code> as random effects in the following models but note that having only two and three levels respectively, it is advisable to keep them as fixed.</p>
<pre>
LM &lt;- lm(total.fruits ~ rack + nutrient + amd + status)
summary(LM)
par(mfrow = c(2,2))
plot(LM)
</pre>
<p><img data-orig-file="https://poissonisfish.files.wordpress.com/2017/12/rplot39.png?w=456" data-orig-size="700,600" data-medium-file="https://poissonisfish.files.wordpress.com/2017/12/rplot39.png?w=456?w=300" data-attachment-id="4414" data-image-meta="{" data-image-description="" src="https://poissonisfish.files.wordpress.com/2017/12/rplot39.png?w=456" data-permalink="https://poissonisfish.wordpress.com/2017/12/11/linear-mixed-effect-models-in-r/rplot-10/" data-large-file="https://poissonisfish.files.wordpress.com/2017/12/rplot39.png?w=456?w=700" alt="Rplot" data-image-title="Rplot" sizes="(max-width: 700px) 100vw, 700px" data-comments-opened="1" class="wp-image-4414" data-recalc-dims="1"></p>
<p>These diagnostic plots show that the residuals of the classic linear model poorly qualify as normally distributed. Because we have no obvious outliers, the leverage analysis provides acceptable results. We will try to improve the distribution of the residuals using LMMs.</p>
<h2>Generalized linear model</h2>
<p>We need to build a GLM as a benchmark for the subsequent LMMs. This model can be fit without random effects, just like a <code>lm</code> but employing ML or REML estimation, using the <code>gls</code> function. Hence, it can be used as a proper null model with respect to random effects. The GLM is also sufficient to tackle heterogeneous variance in the residuals by leveraging different types of variance and correlation functions, when no random effects are present (see arguments <code>correlation</code> and <code>weights</code>).</p>
<pre>
GLM &lt;- gls(total.fruits ~ rack + nutrient + amd + status,
method = &quot;ML&quot;)
summary(GLM)
</pre>
<p>At this point you might consider comparing the GLM and the classic linear model and note they are identical. Also, you might wonder why are we using LM instead of REML – as hinted in the introduction, REML comparisons are meaningless in LMMs that differ in their fixed effects. Therefore, we will base all of our comparisons on LM and only use the REML estimation on the final, optimal model.</p>
<h2>Optimal random structure</h2>
<p>Let’s fit our first LMM with all fixed effects used in the GLM and introducing <code>reg</code>, <code>popu</code>, <code>gen</code>, <code>reg/popu</code>, <code>reg/gen</code>, <code>popu/gen</code> and <code>reg/popu/gen</code> as random intercepts, separately.</p>
<p>In order to compare LMMs (and GLM), we can use the function <code>anova</code><strong> </strong>(note that it does not work for <code>lmer</code> objects) to compute the likelihood ratio test (LRT). This test will determine if the models are significantly different with respect to goodness-of-fit, as weighted by the trade-off between variance explained and degrees-of-freedom. The model fits are also evaluated based on the Akaike (AIC) and Bayesian information criteria (BIC) – the smaller their value, the better the fit.</p>
<pre>
lmm1 &lt;- lme(total.fruits ~ rack + nutrient + amd + status,
random = ~1|reg, method = &quot;ML&quot;)
lmm2 &lt;- lme(total.fruits ~ rack + nutrient + amd + status,
random = ~1|popu, method = &quot;ML&quot;)
lmm3 &lt;- lme(total.fruits ~ rack + nutrient + amd + status,
random = ~1|gen, method = &quot;ML&quot;)
lmm4 &lt;- lme(total.fruits ~ rack + nutrient + amd + status,
random = ~1|reg/popu, method = &quot;ML&quot;)
lmm5 &lt;- lme(total.fruits ~ rack + nutrient + amd + status,
random = ~1|reg/gen, method = &quot;ML&quot;)
lmm6 &lt;- lme(total.fruits ~ rack + nutrient + amd + status,
random = ~1|popu/gen, method = &quot;ML&quot;)
lmm7 &lt;- lme(total.fruits ~ rack + nutrient + amd + status,
random = ~1|reg/popu/gen, method = &quot;ML&quot;)
anova(GLM, lmm1, lmm2, lmm3, lmm4, lmm5, lmm6, lmm7)
</pre>
<p>We could now base our selection on the AIC, BIC or log-likelihood. Considering most models are undistinguishable with respect to the goodness-of-fit, I will select <code>lmm6</code> and <code>lmm7</code>  as the two best models so that we have more of a random structure to look at. Take a look into the distribution of the random effects with <code>plot(ranef(MODEL))</code>. We next proceed to incorporate random slopes.</p>
<p>There is the possibility that the different researchers from the different regions might have handled and fertilized plants differently, thereby exerting slightly different impacts. Let’s update <code>lmm6</code> and <code>lmm7</code> to include random slopes with respect to <code>nutrient</code>. We first need to setup a control setting that ensures the new models converge.</p>
<pre>
# Set optimization pars
ctrl &lt;- lmeControl(opt=&quot;optim&quot;)
lmm6.2 &lt;- update(lmm6, .~., random = ~nutrient|popu/gen, control = ctrl)
lmm7.2 &lt;- update(lmm7, .~., random = ~nutrient|reg/popu/gen, control = ctrl)
anova(lmm6, lmm6.2, lmm7, lmm7.2) # both models improved
anova(lmm6.2, lmm7.2) # similar fit; lmm6.2 more parsimonious
summary(lmm6.2)
</pre>
<p>Assuming a level of significance <img alt="alpha = 0.05 " title="alpha = 0.05 " src="https://s0.wp.com/latex.php?latex=%5Calpha+%3D+0.05+&bg=f9f9f9&%23038;fg=555555&%23038;s=1" class="latex">, the inclusion of random slopes with respect to <code>nutrient</code> improved both <code>lmm6</code> and <code>lmm7</code>. Comparing <code>lmm6.2</code> and<code>lmm7.2</code> head-to-head provides no evidence for differences in fit, so we select the simpler model,<code>lmm6.2</code>. Let’s check how the random intercepts and slopes distribute in the highest level (<em>i.e.</em> <code>gen</code> within <code>popu</code>).</p>
<pre>
plot(ranef(lmm6.2, level = 2))
</pre>
<p><img data-orig-file="https://poissonisfish.files.wordpress.com/2017/12/rplot40.png?w=456" data-orig-size="700,350" data-medium-file="https://poissonisfish.files.wordpress.com/2017/12/rplot40.png?w=456?w=300" data-attachment-id="4415" data-image-meta="{" data-image-description="" src="https://poissonisfish.files.wordpress.com/2017/12/rplot40.png?w=456" data-permalink="https://poissonisfish.wordpress.com/2017/12/11/linear-mixed-effect-models-in-r/rplot-9/" data-large-file="https://poissonisfish.files.wordpress.com/2017/12/rplot40.png?w=456?w=700" alt="Rplot" data-image-title="Rplot" sizes="(max-width: 700px) 100vw, 700px" data-comments-opened="1" class="wp-image-4415" data-recalc-dims="1"></p>
<p>The random intercepts (left) appear to be normally distributed, except for genotype <code>34</code>, biased towards negative values. This could warrant repeating the entire analysis without this genotype. The random slopes (right), on the other hand, are rather normally distributed. Interestingly, there is a negative correlation of -0.61 between random intercepts and slopes, suggesting that genotypes with low baseline TFPP tend to respond better to fertilization. Try <code>plot(ranef(lmm6.2, level = 1))</code> to observe the distributions at the level of <code>popu</code> only. Next, we will use QQ plots to compare the residual distributions between the GLM and <code>lmm6.2</code> to gauge the relevance of the random effects.</p>
<pre>
# QQ plots (drawn to the same scale!)
par(mfrow = c(1,2))
lims &lt;- c(-3.5,3.5)
qqnorm(resid(GLM, type = &quot;normalized&quot;),
xlim = lims, ylim = lims,main = &quot;GLM&quot;)
abline(0,1, col = &quot;red&quot;, lty = 2)
qqnorm(resid(lmm6.2, type = &quot;normalized&quot;),
xlim = lims, ylim = lims, main = &quot;lmm6.2&quot;)
abline(0,1, col = &quot;red&quot;, lty = 2)
</pre>
<p><img data-orig-file="https://poissonisfish.files.wordpress.com/2017/12/rplot33.png?w=456" data-orig-size="700,350" data-medium-file="https://poissonisfish.files.wordpress.com/2017/12/rplot33.png?w=456?w=300" data-attachment-id="4407" data-image-meta="{" data-image-description="" src="https://poissonisfish.files.wordpress.com/2017/12/rplot33.png?w=456" data-permalink="https://poissonisfish.wordpress.com/2017/12/11/linear-mixed-effect-models-in-r/rplot-7/" data-large-file="https://poissonisfish.files.wordpress.com/2017/12/rplot33.png?w=456?w=700" alt="Rplot" data-image-title="Rplot" sizes="(max-width: 700px) 100vw, 700px" data-comments-opened="1" class="wp-image-4407" data-recalc-dims="1"></p>
<p>The improvement is clear. Bear in mind these results do not change with REML estimation. Try different arrangements of random effects with nesting and random slopes, explore as much as possible!</p>
<h2>Optimal fixed structure</h2>
<p>Now that we are happy with the random structure, we will look into the summary of the optimal model so far (<em>i.e. </em><code>lmm6.2</code>) and determine if we need to modify the fixed structure.</p>
<pre>
summary(lmm6.2)
</pre>
<p>All effects are significant with <img alt="alpha = 0.05 " title="alpha = 0.05 " src="https://s0.wp.com/latex.php?latex=%5Calpha+%3D+0.05+&bg=f9f9f9&%23038;fg=555555&%23038;s=1" class="latex">, except for one of the levels from <code>status</code> that represents transplanted plants. Given the significant effect from the other two levels, we will keep <code>status</code> and all current fixed effects. Just for fun, let’s add the interaction term <code>nutrient:amd</code> and see if there is any significant improvement in fit.</p>
<pre>
lmm8 &lt;- update(lmm6.2, .~. + nutrient:amd)
summary(lmm8)
anova(lmm8, lmm6.2)
</pre>
<p>The addition of the interaction was non-significant with respect to both <img alt="beta " title="beta " src="https://s0.wp.com/latex.php?latex=%5Cbeta+&bg=f9f9f9&%23038;fg=555555&%23038;s=1" class="latex"> and the goodness-of-fit, so we will drop it. Note that it is not a good idea to add new terms after optimizing the random structure, I did so only because otherwise there would be nothing to do with respect to the fixed structure.</p>
<h2>Fit optimal model with REML</h2>
<p>We could play a lot more with different model structures, but to keep it simple let’s finalize the analysis by fitting the <code>lmm6.2</code> model using REML and finally identifying and understanding the differences in the main effects caused by the introduction of random effects.</p>
<pre>
finalModel &lt;- update(lmm6.2, .~., method = &quot;REML&quot;)
summary(finalModel)
</pre>
<p>We will now contrast our REML-fitted final model<strong> </strong>against a REML-fitted GLM and determine the impact of incorporating random intercept and slope, with respect to <code>nutrient</code>, at the level of <code>popu/gen</code>. Therefore, both will be given the same fixed effects and estimated using REML.</p>
<pre>
dev.off() # Reset previous graphical pars
# New GLM, updated from the first by estimating with REML
GLM2 &lt;- update(GLM, .~., method = &quot;REML&quot;)
# Plot side by side, beta with respective SEs
plot(coef(GLM2), xlab = &quot;Fixed Effects&quot;, ylab = expression(beta), axes = F,
pch = 16, col = &quot;black&quot;, ylim = c(-.9,2.2))
stdErrors &lt;- coef(summary(GLM2))[,2]
segments(x0 = 1:6, x1 = 1:6, y0 = coef(GLM2) - stdErrors, y1 = coef(GLM2) + stdErrors,
col = &quot;black&quot;)
axis(2)
abline(h = 0, col = &quot;grey&quot;, lty = 2)
axis(1, at = 1:6,
labels = c(&quot;Intercept&quot;, &quot;Rack&quot;, &quot;Nutrient (Treated)&quot;,&quot;AMD (Unclipped)&quot;,&quot;Status (PP)&quot;,
&quot;Status (Transplant)&quot;), cex.axis = .7)
# LMM
points(1:6 + .1, fixef(finalModel), pch = 16, col = &quot;red&quot;)
stdErrorsLMM &lt;- coef(summary(finalModel))[,2]
segments(x0 = 1:6 + .1, x1 = 1:6 + .1, y0 = fixef(finalModel) - stdErrorsLMM, y1 = fixef(finalModel) + stdErrorsLMM, col = &quot;red&quot;)
# Legend
legend(&quot;topright&quot;, legend = c(&quot;GLM&quot;,&quot;LMM&quot;), text.col = c(&quot;black&quot;,&quot;red&quot;), bty = &quot;n&quot;)
</pre>
<p><img data-orig-file="https://poissonisfish.files.wordpress.com/2017/12/rplot34.png?w=456" data-orig-size="700,500" data-medium-file="https://poissonisfish.files.wordpress.com/2017/12/rplot34.png?w=456?w=300" data-attachment-id="4408" data-image-meta="{" data-image-description="" src="https://poissonisfish.files.wordpress.com/2017/12/rplot34.png?w=456" data-permalink="https://poissonisfish.wordpress.com/2017/12/11/linear-mixed-effect-models-in-r/rplot-8/" data-large-file="https://poissonisfish.files.wordpress.com/2017/12/rplot34.png?w=456?w=700" alt="Rplot" data-image-title="Rplot" sizes="(max-width: 700px) 100vw, 700px" data-comments-opened="1" class="wp-image-4408" data-recalc-dims="1"></p>
<p>The figure above depicts the estimated <img alt="beta " title="beta " src="https://s0.wp.com/latex.php?latex=%5Cbeta+&bg=f9f9f9&%23038;fg=555555&%23038;s=1" class="latex"> from the different fixed effects, including the intercept, for the GLM (black) and the final LMM (red). Error bars represent the corresponding standard errors (SE). Overall the results are similar but uncover two important differences. First, for all fixed effects except the intercept and <code>nutrient</code>, the SE is smaller in the LMM. Second, the relative effects from two levels of <code>status</code> are opposite. With the consideration of random effects, the LMM estimated a more negative effect of culturing in Petri plates on TFPP, and conversely a less negative effect of transplantation.</p>
<pre>
plot(finalModel)
</pre>
<h2><img data-orig-file="https://poissonisfish.files.wordpress.com/2017/12/rplot35.png?w=456" data-orig-size="700,350" data-medium-file="https://poissonisfish.files.wordpress.com/2017/12/rplot35.png?w=456?w=300" data-attachment-id="4409" data-image-meta="{" data-image-description="" src="https://poissonisfish.files.wordpress.com/2017/12/rplot35.png?w=456" data-permalink="https://poissonisfish.wordpress.com/2017/12/11/linear-mixed-effect-models-in-r/rplot-6/" data-large-file="https://poissonisfish.files.wordpress.com/2017/12/rplot35.png?w=456?w=700" alt="Rplot" data-image-title="Rplot" sizes="(max-width: 700px) 100vw, 700px" data-comments-opened="1" class="wp-image-4409" data-recalc-dims="1"></h2>
<p>The distribution of the residuals as a function of the predicted TFPP values in the LMM is still similar to the first panel in the diagnostic plots of the classic linear model. The usage of additional predictors and generalized additive models would likely improve it.</p>
<h2>Conclusions</h2>
<p>Now that we account for genotype-within-region random effects, how do we interpret the LMM results?</p>
<p>Plants that were placed in the first rack, left unfertilized, clipped and grown normally have an average TFPP of 2.15. This is the value of the estimated grand mean (<em>i.e.</em> intercept), and the predicted TFPP when all other factors and levels do not apply. For example, a plant grown under the same conditions but placed in the second rack will be predicted to have a smaller yield, more precisely of <img alt="ln(TFPP) = beta_{intercept} + beta_{Rack} = 2.15 + (-0.75) = 1.4 " title="ln(TFPP) = beta_{intercept} + beta_{Rack} = 2.15 + (-0.75) = 1.4 " src="https://s0.wp.com/latex.php?latex=ln%28TFPP%29+%3D+%5Cbeta_%7Bintercept%7D+%2B+%5Cbeta_%7BRack%7D+%3D+2.15+%2B+%28-0.75%29+%3D+1.4+&bg=f9f9f9&%23038;fg=555555&%23038;s=1" class="latex">. To these reported yield values, we still need to add the random intercepts predicted for region and genotype within region (which are tiny values, by comparison; think of them as a small adjustment). Moreover, we can state that</p>
<ul>
<li>Fertilized plants produce more fruits than those kept unfertilized. This was the strongest main effect and represents a very sensible finding.</li>
<li>Plants grown in the second rack produce less fruits than those in the first rack. This was the second strongest main effect identified. Could this be due to light / water availability?</li>
<li>Simulated herbivory (AMD) negatively affects fruit yield. This is also a sensible finding – when plants are attacked, more energy is allocated to build up biochemical defence mechanisms against herbivores and pathogens, hence compromising growth and eventually fruit yield.</li>
<li>Both culturing in Petri plates and transplantation, albeit indistinguishable, negatively affect fruit yield as opposed to normal growth. When conditions are radically changed, plants must adapt swiftly and this comes at a cost as well. Thus, these observations too make perfect sense.</li>
<li>One important observation is that the genetic contribution to fruit yield, as gauged by <code>gen</code>, was normally distributed and adequately modelled as random. One single outlier could eventually be excluded from the analysis. This makes sense assuming plants have evolved universal mechanisms in response to both nutritional status and herbivory that overrule any minor genetic differences among individuals from the same species.</li>
</ul>
<h2>Wrap-up</h2>
<ul>
<li>Always check the residuals and the random effects! While both linear models and LMMs require normally distributed residuals with homogeneous variance, the former assumes independence among observations and the latter normally distributed random effects. Use normalized residuals to establish comparisons.</li>
<li>One key additional advantage of LMMs we did not discuss is that they can handle missing values.</li>
<li>Wide format data should be first converted to long format, using <em>e.g.</em> the R package <a rel="nofollow" href="https://www.statmethods.net/management/reshape.html" target="_blank">reshape</a>.</li>
<li>Variograms are very helpful in determining spatial or temporal dependence in the residuals. In the case of spatial dependence, bubble plots nicely represent residuals in the space the observations were drown from (<em>e.g.</em> latitude and longitude; refer to <a rel="nofollow" href="http://www.springer.com/gb/book/9780387874579" target="_blank">Zuur et al. (2009)</a> for more information).</li>
<li>REML estimation is unbiased but does not allow for comparing models with different fixed structures. Only use the REML estimation on the optimal model.</li>
</ul>
<p>With respect to this particular set of results:</p>
<ul>
<li>The analysis outlined here is not as exhaustive as it should be. Among other things, we did neither initially consider interaction terms among fixed effects nor investigate in sufficient depth the random effects from the optimal model.</li>
<li>The dependent variable (total fruit set per plant) was highly right-skewed and required a log-transformation for basic modeling. The large amount of zeros would in rigour require zero inflated GLMs or similar approaches.</li>
<li>All predictors used in the analysis were categorical factors. We could similarly use an ANOVA model. LMMs are likely more relevant in the presence of quantitative or mixed types of predictors.</li>
</ul>
<p>I would like to thank Hans-Peter Piepho for answering my nagging questions over ResearchGate. I hope these superficial considerations were clear and insightful. I look forward for your suggestions and feedback. My next post will cover a joint multivariate model of multiple responses, the graph-guided fused LASSO (GFLASSO) using a R package I am currently developing. Happy holidays!</p>
<p> <a rel="nofollow" href="https://feeds.wordpress.com/1.0/gocomments/poissonisfish.wordpress.com/1997/" target="_blank"><img border="0" alt="" src="https://feeds.wordpress.com/1.0/comments/poissonisfish.wordpress.com/1997/"></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://poissonisfish.wordpress.com/2017/12/11/linear-mixed-effect-models-in-r/"> poissonisfish</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/X16dPXKyWiI" height="1"></a></div>