<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/generalized-addictive-models-and-mixed-effects-in-agriculture/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://r-video-tutorial.blogspot.com/2017/07/generalized-addictive-models-and-mixed.html"> R tutorial for Spatial Statistics</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<h2>Introduction</h2>
<p>In the previous post I explored the use of linear model in the forms most commonly used in agricultural research.<br>Clearly, when we are talking about linear models we are implicitly assuming that all relations between the dependent variable y and the predictors x are linear. In fact, in a linear model we could specify different shapes for the relation between y and x, for example by including polynomials (read for example: https://datascienceplus.com/fitting-polynomial-regression-r/). However, we can do that only in cases where we can clearly see a particular shape of the relation, for example quadratic. The problem is in many cases we can see from a scatterplot that we have a non-linear distribution of the points, but it is difficult to understand its form. Moreover, in a linear model the interpretation of polynomial coefficients become more difficult and this may decrease their usefulness.<br>An alternative approach is provided by Generalized Addictive Models, which allows us to fit models with non-linear smoothers without specifying a particular shape a priori.</p>
<p>I will not go into much details about the theory behind GAMs. You can refer to these two books (freely available online) to know more:</p>
<p><span>Wood, S.N., 2017. </span><i>Generalized additive models: an introduction with R</i><span>. CRC press.</span><br><span><span>http://reseau-mexico.fr/sites/reseau-mexico.fr/files/igam.pdf</span></span><br><span><span><br></span></span><span>Crawley, M.J., 2012. </span><i>The R book</i><span>. John Wiley &amp; Sons.</span><br><span><span>https://www.cs.upc.edu/~robert/teaching/estadistica/TheRBook.pdf</span></span><br><span><span><br></span></span><br>
<h2></h2>
<h2>Some Background</h2>
<div>As mentioned above, GAM models are more powerful that the other linear model we have seen in previous posts since they allow to include non-linear smoothers into the mix. In mathematical terms GAM solve the following equation:
<div><a rel="nofollow" href="https://i2.wp.com/1.bp.blogspot.com/-5CUyerAemSk/WWM4a8H_IXI/AAAAAAAAXfs/HKOwmlyTtY8RwFyAH8QQu0Ll22aUS3qfwCLcBGAs/s1600/Eq1.png?ssl=1" target="_blank"><img border="0" data-original-height="101" src="https://i0.wp.com/1.bp.blogspot.com/-5CUyerAemSk/WWM4a8H_IXI/AAAAAAAAXfs/HKOwmlyTtY8RwFyAH8QQu0Ll22aUS3qfwCLcBGAs/s640/Eq1.png?resize=450%2C101&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<div></div>
<p>It may seem like a complex equation, but actually it is pretty simple to understand. The first thing to notice is that with GAM we are not necessarily estimating the response directly, i.e. we are not modelling y. In fact, as with GLM we have the possibility to use link functions to model non-normal response variables (and thus perform poisson or logistic regression). Therefore, the term g(μ) is simply the transformation of y needed to “linearize” the model. When we are dealing with a normally distributed response this term is simply replace by y.<br>Now we can explore the second part of the equation, where we have two terms: the parametric and the non-parametric part. In GAM we can include all the parametric terms we can include in lm or glm, for example linear or polynomial terms. The second part is the non-parametric smoother that will be fitted automatically and it is the key point of GAMs.<br>To better understand the difference between the two parts of the equation we can explore an example. Let’s say we have a response variable (normally distributed) and two predictors x1 and x2. We look at the data and we observe a clear linear relation between x1 and y, but a complex curvilinear pattern between x2 and y. Because of this we decide to fit a generalized addictive model that in this particular case will take the following equation:</p>
<div><a rel="nofollow" href="https://i2.wp.com/3.bp.blogspot.com/-Jn9sec9ovyA/WWM7bSo0o3I/AAAAAAAAXf4/67zoZbkGbpUlvYR5N6Ugx9Qhk_28tf9gACLcBGAs/s1600/Eq2.png?ssl=1" target="_blank"><img border="0" data-original-height="95" src="https://i1.wp.com/3.bp.blogspot.com/-Jn9sec9ovyA/WWM7bSo0o3I/AAAAAAAAXf4/67zoZbkGbpUlvYR5N6Ugx9Qhk_28tf9gACLcBGAs/s640/Eq2.png?resize=450%2C95&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p>Since y is normal we do not need the link function g(). Then we are modelling x1 as a linear model with intercept beta zero and coefficient beta one. However, since we observed a curvilinear relation between x2 and y we also including a non-parametric smoothing function to model x2.</p></div>
<h2>Practical Example</h2>
<div>In this tutorial we will work once again with the package agridat so that we can work directly with real data in agriculture. Other packages we will use are ggplot2, moments, pscl and MuMIn:
<pre><code> library(agridat)  <br> library(ggplot2)  <br> library(moments)  <br> library(pscl)  <br> library(MuMIn)  <br></code></pre>
<p></div>
<p>In R there are two packages to fit generalized addictive models, I will talk about the package mgcv. For an overview of GAMs from the package gam you can refer to this post: https://datascienceplus.com/generalized-additive-models/</p>
<p>The first thing we need to do is install the package mgcv:</p>
<pre><code> install.packages(&quot;mgcv&quot;)  <br> library(mgcv)  <br></code></pre>
<p>Now we can load once again the package lasrosas.corn with measures of yield based on nitrogen treatments, plus topographic position and brightness value (for more info please take a look at my previous post: <a rel="nofollow" href="http://r-video-tutorial.blogspot.co.uk/2017/06/linear-models-anova-glms-and-mixed.html" target="_blank">Linear Models (lm, ANOVA and ANCOVA) in Agriculture</a>). Then we can use the function pairs to plot all variable in scatterplots, colored by topographic position:</p>
<pre><code> dat = lasrosas.corn  <br> attach(dat)  <br> pairs(dat[,4:9], lower.panel = NULL, col=topo)  <br></code></pre>
<p>This produces the following image:</p>
<div><a rel="nofollow" href="https://i1.wp.com/1.bp.blogspot.com/-mzB3rVmS274/WWNj_v59sfI/AAAAAAAAXgE/Cr5v_wR-aBQmr-nlRonL4PSyxFvo6wm1gCLcBGAs/s1600/Fig1.jpeg?ssl=1" target="_blank"><img border="0" data-original-height="877" src="https://i1.wp.com/1.bp.blogspot.com/-mzB3rVmS274/WWNj_v59sfI/AAAAAAAAXgE/Cr5v_wR-aBQmr-nlRonL4PSyxFvo6wm1gCLcBGAs/s640/Fig1.jpeg?resize=450%2C877&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p>In the previous post we only fitted linear models to these data, and therefore the relations between yield and all other predictors were always modelled as lines. However, if we look at the scatterplot between yield and bv, we can clearly see a pattern that does not really look linear, with some blue dots that deviates from the main cloud. If these blue dots were not present we would be happy in modelling this relation as linear. In fact we can prove that by only focusing on this plot and removing the level W from topo:</p>
<pre><code> par(mfrow=c(1,2))  <br> plot(yield ~ bv, pch=20, data=dat, xlim=c(100,220))  <br> plot(yield ~ bv, pch=20, data=dat[dat$topo!=&quot;W&quot;,], xlim=c(100,220))  <br></code></pre>
<p>which creates the following plot:</p>
<div><a rel="nofollow" href="https://i1.wp.com/3.bp.blogspot.com/-2DIHEPwTqEo/WWNllhOyvaI/AAAAAAAAXgI/_kCtf4vt4XI2pM75kAA2E6iFepra86iLQCLcBGAs/s1600/Fig2.jpeg?ssl=1" target="_blank"><img border="0" data-original-height="671" src="https://i1.wp.com/3.bp.blogspot.com/-2DIHEPwTqEo/WWNllhOyvaI/AAAAAAAAXgI/_kCtf4vt4XI2pM75kAA2E6iFepra86iLQCLcBGAs/s640/Fig2.jpeg?resize=450%2C671&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p>From this plot it is clear that the level W is an anomaly compared to the rest of the dataset. However, even removing this from the dataset does not really produce a linear pattern, but more a quadratic one. For this reason, it may be that if we want to obtain the best possible results in terms of modelling yield we would need to split the data by topographic position. However, for this post we are not interested in this, but only in showing the use of GAMs. Therefore, we will keep all levels of topo and then try to model the relation between yield and topo with a non-parametric smoother.</p>
<pre><code> mod.lm = lm(yield ~ bv)  <br> mod.quad = lm(yield ~ bv + I(bv^2))  <br> mod.gam = gam(yield ~ s(bv), data=dat)  <br></code></pre>
<p>Here we are testing three models: standard linear model, a linear model with a quadratic term and finally a GAM. We do that because clearly we are not sure which model is the best and we want to make sure we do not overfit our data.<br>We can compare these models in the same way we explored in previous posts: by calculating the Akaike Information Criterion (AIC) and with an F test.</p>
<pre><code> > AIC(mod.lm, mod.quad, mod.gam)  <br>         df   AIC  <br> mod.lm  3.000000 29005.32  <br> mod.quad 4.000000 28924.18  <br> mod.gam 7.738304 28853.72  <br> > anova(mod.lm, mod.quad, mod.gam, test=&quot;F&quot;)  <br> Analysis of Variance Table  <br> Model 1: yield ~ bv  <br> Model 2: yield ~ bv + I(bv^2)  <br> Model 3: yield ~ s(bv)  <br>  Res.Df  RSS   Df Sum of Sq   F  Pr(>F)    <br> 1 3441.0 917043                     <br> 2 3440.0 895165 1.0000   21879 85.908 &lt; 2.2e-16 ***  <br> 3 3436.3 875130 3.7383   20034 21.043 3.305e-16 ***  <br> ---  <br> Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1  <br></code></pre>
<p>The AIC suggests that the GAM is slightly more accurate that the other two, even with more degrees of freedom. The F test again results in significant difference between models, thus suggesting that we should use the more complex model.</p>
<p>We can look at the difference in fitting of the three models graphically first using the standard plotting function and then with ggplot2:</p>
<pre><code> plot(yield ~ bv, pch=20)  <br> abline(mod.lm,col=&quot;blue&quot;,lwd=2)  <br> lines(50:250,predict(mod.gam, newdata=data.frame(bv=50:250)),col=&quot;red&quot;,lwd=2)  <br> lines(50:250,predict(mod.quad, newdata=data.frame(bv=50:250)),col=&quot;green&quot;,lwd=2)  <br></code></pre>
<p>This produces the following image:</p>
<div><a rel="nofollow" href="https://i1.wp.com/2.bp.blogspot.com/-3IIvEr36FOo/WWNoZ7AroGI/AAAAAAAAXgM/ezU36-Z7UU4Y8fC4VbqnGmTtphPsp_UKQCLcBGAs/s1600/Fig3.jpeg?ssl=1" target="_blank"><img border="0" data-original-height="671" src="https://i0.wp.com/2.bp.blogspot.com/-3IIvEr36FOo/WWNoZ7AroGI/AAAAAAAAXgM/ezU36-Z7UU4Y8fC4VbqnGmTtphPsp_UKQCLcBGAs/s640/Fig3.jpeg?resize=450%2C671&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p>The same can be achieved with ggplot2:</p>
<pre><code> ggplot(data=dat, aes(x=bv, y=yield)) +  <br>      geom_point(aes(col=dat$topo))  +  <br>      geom_smooth(method = &quot;lm&quot;, se = F, col=&quot;red&quot;)+  <br>      geom_smooth(method=&quot;gam&quot;, formula=y~s(x), se = F, col=&quot;blue&quot;) +  <br>      stat_smooth(method=&quot;lm&quot;, formula=yield~x+I(x^2),se = F, col=&quot;green&quot;)  <br></code></pre>
<p>which produces the following:</p>
<div><a rel="nofollow" href="https://i0.wp.com/3.bp.blogspot.com/-un18wMT4TY4/WWNo2jx1kXI/AAAAAAAAXgQ/ZDMIn7PAzwwEhznwdY1xLWqudP98WXxmQCLcBGAs/s1600/Fig4.jpeg?ssl=1" target="_blank"><img border="0" data-original-height="671" src="https://i1.wp.com/3.bp.blogspot.com/-un18wMT4TY4/WWNo2jx1kXI/AAAAAAAAXgQ/ZDMIn7PAzwwEhznwdY1xLWqudP98WXxmQCLcBGAs/s640/Fig4.jpeg?resize=450%2C671&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p>This second image is even more informative because when we decide to use a categorical variable to color the dots, ggplot2 automatically creates a legend for it, so we know which level causes the shift in the data (i.e. W).</p>
<p>As you can see all of these lines do not really fit the data perfectly, since the large cloud around 100 in yield and 180 in bv is not considered. However, the blue line of the non-parametric smoother seems to better catch the violet dots on the left and also bends when reaches the cloud, mimicking the quadratic behavior we observed before.</p>
<p>With GAM we can still use the function summary to look at the model in details:</p>
<pre><code> > summary(mod.gam)  <br> Family: gaussian   <br> Link function: identity   <br> Formula:  <br> yield ~ s(bv)  <br> Parametric coefficients:  <br>       Estimate Std. Error t value Pr(>|t|)    <br> (Intercept)  69.828   0.272  256.7  &lt;2e-16 ***  <br> ---  <br> Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1  <br> Approximate significance of smooth terms:  <br>     edf Ref.df   F p-value    <br> s(bv) 5.738 6.919 270.7 &lt;2e-16 ***  <br> ---  <br> Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1  <br> R-sq.(adj) = 0.353  Deviance explained = 35.4%  <br> GCV = 255.17 Scale est. = 254.68  n = 3443  <br></code></pre>
<p>The interpretation is similar to linear models, and probably a bit easier that with GLM since in GAM we also have an R Squared directly from the summary output. As you can see the smooth term is highly significant and we can see its estimated degrees of freedom (around 6) and its F and p values. At the bottom of the output we see a numerical value for GCV, which stands for Generalized Cross Validation Score. This is what the model tries to reduce by default and it is given by the equation below:</p>
<div><a rel="nofollow" href="https://i0.wp.com/1.bp.blogspot.com/-G1Iwz1gxAik/WWczkSOvxnI/AAAAAAAAXjw/CsUz1GTnxi0031yLIzcT48qoq843PEFvwCLcBGAs/s1600/Eq3.png?ssl=1" target="_blank"><img border="0" data-original-height="175" src="https://i1.wp.com/1.bp.blogspot.com/-G1Iwz1gxAik/WWczkSOvxnI/AAAAAAAAXjw/CsUz1GTnxi0031yLIzcT48qoq843PEFvwCLcBGAs/s640/Eq3.png?resize=450%2C175&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p>
<div>where D is the deviance, n is the number of samples, and df the effective degrees of freedom of the model. for more info please refer to Wood’s book. I read on-line in an answer on StackOverflow that GCV may produce underfitting, I am not completely sure about this because I have not found any mention of it on official documentations. However, just in case later on I will show you how to fit the smoother with REML, which according to StackOverflow should solve the issue with underfitting.</div>
<div></div>
<h3>Include more parameters</h3>
<p>Now that we have a general idea about what function to fit for bv we can add more predictors and try to create a more accurate model.</p>
<pre><code> > #Include more predictors  <br> > mod.lm = lm(yield ~ nitro + nf + topo + bv)  <br> > mod.gam = gam(yield ~ nitro + nf + topo + s(bv), data=dat)  <br> >   <br> > #Comparison R Squared  <br> > summary(mod.lm)$adj.r.squared  <br> [1] 0.5211237  <br> > summary(mod.gam)$r.sq  <br> [1] 0.5292042  <br></code></pre>
<p>In the code above we are comparing two models with all of the predictors we have in the datasets. As you can see there is not much difference in the two models in terms of R Squared, so both model are able to explain pretty much the same level of variation in yield.</p>
<p>However, as you remember from above, we clearly noticed changes in bv depending on topo, and we also noticed that if we exclude certain topographic categories the behavior of the curve would probably change. We can include this new hypothesis in the model by using the option by within s, to fit a non-parametric smoother to each topographic factor individually.</p>
<pre><code> > mod.gam2 = gam(yield ~ nitro + nf * topo + s(bv, by=topo), data=dat)  <br> >   <br> > summary(mod.gam2)$r.sq  <br> [1] 0.5612617  <br></code></pre>
<p>As you can see if we fit a curve to each subset of the plot above we can increase the R Squared, and therefore explain more variation in yield.<br>We can further explore the difference in models with function AIC and anova, as we’ve seen in previous posts:</p>
<pre><code> > AIC(mod.lm, mod.gam, mod.gam2)  <br>         df   AIC  <br> mod.lm  12.00000 27815.23  <br> mod.gam 18.60852 27763.83  <br> mod.gam2 42.22616 27548.63  <br> >   <br> > #F test  <br> > anova(mod.lm, mod.gam, mod.gam2, test=&quot;F&quot;)  <br> Analysis of Variance Table  <br> Model 1: yield ~ nitro + nf + topo + bv  <br> Model 2: yield ~ nitro + nf + topo + s(bv)  <br> Model 3: yield ~ nitro + nf * topo + s(bv, by = topo)  <br>  Res.Df  RSS   Df Sum of Sq   F  Pr(>F)    <br> 1 3432.0 645661                      <br> 2 3425.4 633656 6.6085   12005 10.525 1.512e-12 ***  <br> 3 3401.8 587151 23.6176   46505 11.408 &lt; 2.2e-16 ***  <br> ---  <br> Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1  <br></code></pre>
<p>The AIC is lower for mod.gam2, and the F test suggest it is significantly different from the other, meaning that we should use the more complex model.</p>
<p>Another way of assessing the accuracy of our two models would be to use some diagnostic plots. Let’s start with the model with a non-parametric smoother fitted to the whole datasets (mod.gam):</p>
<pre><code> plot(mod.gam, all.terms=F, residuals=T, pch=20)  <br></code></pre>
<p>which produce the following image:</p>
<div><a rel="nofollow" href="https://i0.wp.com/3.bp.blogspot.com/-fbJECOueFUc/WWTMhj4cw_I/AAAAAAAAXhU/YOToDpLiyn8T29ZK0AefH6sGduylqJLAwCLcBGAs/s1600/Fig5.jpeg?ssl=1" target="_blank"><img border="0" data-original-height="671" src="https://i0.wp.com/3.bp.blogspot.com/-fbJECOueFUc/WWTMhj4cw_I/AAAAAAAAXhU/YOToDpLiyn8T29ZK0AefH6sGduylqJLAwCLcBGAs/s640/Fig5.jpeg?resize=450%2C671&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p>This plot can be interpreted exactly like the fitted vs. residuals plot we produced for the post about linear model (see here: <a rel="nofollow" href="http://r-video-tutorial.blogspot.co.uk/2017/06/linear-models-anova-glms-and-mixed.html" target="_blank">Linear Models (lm, ANOVA and ANCOVA) in Agriculture</a>). For the model to be good we would expect this line to be horizontal and the spread to be more or less homogeneous. However, this is clearly not the case and this strongly suggest our model is not a good one.<br>Now let’s take a look at the same plot for mod.gam2, the one where we fitted a curve for each level of topo:</p>
<pre><code> par(mfrow=c(2,2))  <br> plot(mod.gam2, all.terms=F, residuals=T, pch=20)  <br></code></pre>
<p>In this case we need to use the function par to create 4 sub-plots within the plotting window. This is because now the model fits a curve for each of the four categories in topo, so four plots will be created.</p>
<div><a rel="nofollow" href="https://i1.wp.com/4.bp.blogspot.com/-pv7Mg-0_iw0/WWTNrgicFVI/AAAAAAAAXhY/Ttpnxz6Xgog5PuveELferW2LX8MGcGN3gCLcBGAs/s1600/Fig6.jpeg?ssl=1" target="_blank"><img border="0" data-original-height="815" src="https://i0.wp.com/4.bp.blogspot.com/-pv7Mg-0_iw0/WWTNrgicFVI/AAAAAAAAXhY/Ttpnxz6Xgog5PuveELferW2LX8MGcGN3gCLcBGAs/s640/Fig6.jpeg?resize=450%2C815&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p>The result is clearly much better. All lines are more or less horizontal, even tough in some case the spread of the confidence intervals in uneven. However, this model is clearly a step forward in term of accuracy compared to mod.gam.</p>
<p>Another useful function for producing diagnostic plots is gam.check:</p>
<pre><code> par(mfrow=c(2,2))  <br> gam.check(mod.gam2)  <br></code></pre>
<p>which creates the following:</p>
<div><a rel="nofollow" href="https://i1.wp.com/1.bp.blogspot.com/-iDHpusIQrfI/WWTOXSgeRTI/AAAAAAAAXhc/UKUDH1Liq0UiuoLeRmlOaiBWaGzHnE1BQCLcBGAs/s1600/Fig7.jpeg?ssl=1" target="_blank"><img border="0" data-original-height="671" src="https://i0.wp.com/1.bp.blogspot.com/-iDHpusIQrfI/WWTOXSgeRTI/AAAAAAAAXhc/UKUDH1Liq0UiuoLeRmlOaiBWaGzHnE1BQCLcBGAs/s640/Fig7.jpeg?resize=450%2C671&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p>This shows similar plots to what we see in the previous post about linear models. Again we are aiming at normally distributed residuals. Moreover, the plot residuals vs. fitted should show a cloud centered around 0 and with more or less equal variance throughout the range of fitted values, which is approximately what we see here.</p>
<p>
<h3>Changing Parameters</h3>
<div>The function s, used to fit non-parametric smoother, can take a series of option that changes it behavior. We will now look at some of them:
</div>
<div>
<pre><code> mod.gam1 = gam(yield ~ s(bv), data=dat)  <br> mod.gam2 = gam(yield ~ s(bv), data=dat, gamma=1.4)   <br> mod.gam3 = gam(yield ~ s(bv), data=dat, method=&quot;REML&quot;)  <br> mod.gam4 = gam(yield ~ s(bv, bs=&quot;cr&quot;), data=dat) #All options for bs at help(smooth.terms)  <br> mod.gam5 = gam(yield ~ s(bv, bs=&quot;ps&quot;), data=dat)  <br> mod.gam6 = gam(yield ~ s(bv, k=2), data=dat)  <br></code></pre>
<div>The first line is the standard use, without any option and we will use it just for comparison. The second call (mod.gam2) changes the gamma, which increases the “penalty” per increment in degree of freedom. Its default value is 1, but Wood suggest that increasing it to 1.4 can reduce over-fitting (Pag. 227 of Wood’s book, link on top of the page). The third model fits the GAM using REML instead of the standard GCV score, which should provide a more robust fitting. The fourth and fifth models use the option bs within the function s to change the way the curve is fitted. In mod.gam4, cr stands for cubic regression spline, while in mod.gam5 ps stands for P-Splines. There are several options available for bs and you can look at them with help(smooth.terms). Each of these option comes with advantages and disadvantages; to know more about this topic you can read pag. 222 from Wood’s book.<br>The final model (mod.gam6) changes the dimension of the curve, with which we can select the maximum degrees of freedom (default value is 10). In this case we are basically telling R to fit a quadratic curve.<br>We can plot all the lines generated from the models above to have an idea of individual impacts:
<pre><code> plot(yield ~ bv, pch=20)  <br> lines(50:250,predict(mod.gam1, newdata=data.frame(bv=50:250)),col=&quot;blue&quot;,lwd=2)  <br> lines(50:250,predict(mod.gam2, newdata=data.frame(bv=50:250)),col=&quot;red&quot;,lwd=2)  <br> lines(50:250,predict(mod.gam3, newdata=data.frame(bv=50:250)),col=&quot;green&quot;,lwd=2)  <br> lines(50:250,predict(mod.gam4, newdata=data.frame(bv=50:250)),col=&quot;yellow&quot;,lwd=2)  <br> lines(50:250,predict(mod.gam5, newdata=data.frame(bv=50:250)),col=&quot;orange&quot;,lwd=2)  <br> lines(50:250,predict(mod.gam6, newdata=data.frame(bv=50:250)),col=&quot;violet&quot;,lwd=2)  <br></code></pre>
<p>
<div><a rel="nofollow" href="https://i1.wp.com/2.bp.blogspot.com/-BcrSw_Hd1kg/WWeTHQBX60I/AAAAAAAAXkw/RVn3ql4y4AoG6At3rFpqYYKDbYgF8GyJACLcBGAs/s1600/Fig8.jpeg?ssl=1" target="_blank"><img border="0" data-original-height="671" src="https://i1.wp.com/2.bp.blogspot.com/-BcrSw_Hd1kg/WWeTHQBX60I/AAAAAAAAXkw/RVn3ql4y4AoG6At3rFpqYYKDbYgF8GyJACLcBGAs/s640/Fig8.jpeg?resize=450%2C671&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p>As you can see the violet line is basically a quadratic curve, while the rest are quite complex in shape. In particular, the orange line created with P-splines looks like is overfitting the data, while the other look generally the same.</p>
<h3>Count Data – Poisson Regression</h3>
</div>
</div>
<div>GAM can be used with all the distributions and link function we have explored for GLM (<a rel="nofollow" href="http://r-video-tutorial.blogspot.co.uk/2017/07/generalized-linear-models-and-mixed.html" target="_blank">Generalized Linear Models</a>). To explore this we are going to use another dataset from the package agridat: named mead.cauliflower. This dataset presents leaves for cauliflower plants at different times.</div>
<div></div>
<pre><code> dat = mead.cauliflower  <br> str(dat)  <br> attach(dat)  <br> pairs(dat, lower.panel = NULL)   <br></code></pre>
<div>
<div><a rel="nofollow" href="https://i0.wp.com/1.bp.blogspot.com/-B9WBgEW77kQ/WWeUXKjYI0I/AAAAAAAAXk0/kNkK3yd2FKwwH8C4gotc_DkcCU2Fl7KOACLcBGAs/s1600/Fig9.jpeg?ssl=1" target="_blank"><img border="0" data-original-height="671" src="https://i1.wp.com/1.bp.blogspot.com/-B9WBgEW77kQ/WWeUXKjYI0I/AAAAAAAAXk0/kNkK3yd2FKwwH8C4gotc_DkcCU2Fl7KOACLcBGAs/s640/Fig9.jpeg?resize=450%2C671&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p>From the pairs plot it seems that a linear model would probably describe the relation between leaves and the variable degdays pretty well. However, since we are talking about GAMs we will try to fit a generalized addictive model and see how it compares to that standard GLM.</p>
<pre><code> pois.glm = glm(leaves ~ year + degdays, data=dat, family=c(&quot;poisson&quot;))  <br> pois.gam = gam(leaves ~ year + s(degdays), data=dat, family=c(&quot;poisson&quot;))  <br></code></pre>
<p>as you can see there are only minor differences in the syntax between the two lines. We are still using the option family to specify that we want the poisson distribution for the error term, plus the log link (used by default so we do not need to specify it).<br>To compare the model we can again use AIC and anova:</p>
<pre><code> > AIC(pois.glm, pois.gam)  <br>         df   AIC  <br> pois.glm 3.000000 101.4505  <br> pois.gam 3.431062 101.1504  <br> >   <br> > anova(pois.glm, pois.gam)  <br> Analysis of Deviance Table  <br> Model 1: leaves ~ year + degdays  <br> Model 2: leaves ~ year + s(degdays)  <br>  Resid. Df Resid. Dev   Df Deviance  <br> 1  11.000   6.0593           <br> 2  10.569   4.8970 0.43106  1.1623  <br></code></pre>
<p>Both results suggest that in fact a GAM for this dataset is not needed, since it is only slightly different from the GLM model. We could also compare the R Squared of the two models, using the function to compute it for GLM we tested in the previous post:</p>
<pre><code> > pR2(pois.glm)  <br>      llh   llhNull      G2   McFadden     r2ML     r2CU   <br>  -47.7252627 -132.3402086 169.2298918  0.6393744  0.9999944  0.9999944   <br> > r.squaredLR(pois.glm)  <br> [1] 0.9999944  <br> attr(,&quot;adj.r.squared&quot;)  <br> [1] 0.9999944  <br> >   <br> > summary(pois.gam)$r.sq  <br> [1] 0.9663474  <br></code></pre>
<p>For overdispersed data we have the option to use both the quasipoisson and the negative binomial distributions:</p>
<pre><code> pois.gam.quasi = gam(leaves ~ year + s(degdays), data=dat, family=c(&quot;quasipoisson&quot;))  <br> pois.gam.nb = gam(leaves ~ year + s(degdays), data=dat, family=nb())  <br></code></pre>
<p>For more info about the use of the negative binomial please look at this article:<br><a rel="nofollow" href="http://astrostatistics.psu.edu/su07/R/html/mgcv/html/gam.neg.bin.html" target="_blank">GAMs with the negative binomial distribution</a></p>
<p>
<h3>Logistic Regression</h3>
</div>
<div>Since we can use of the families we have in GLMs we can also use GAM with binary data, the syntax again is very similar to what we used for GLM:
</div>
<div>
<pre><code> dat = johnson.blight  <br> str(dat)  <br> attach(dat)  <br> logit.glm = glm(blight ~ rain.am + rain.ja + precip.m, data=dat, family=binomial)  <br> logit.gam = gam(blight ~ s(rain.am, rain.ja,k=5) + s(precip.m), data=dat, family=binomial)  <br></code></pre>
<p></div>
<div>As you can see we are using an interaction between rain.am and rain.ja in the model, plus another smooth curve fitted only to precip.m.<br>We can compare the two models as follows:
<pre><code> > anova(logit.glm, logit.gam, test=&quot;Chi&quot;)  <br> Analysis of Deviance Table  <br> Model 1: blight ~ rain.am + rain.ja + precip.m  <br> Model 2: blight ~ s(rain.am, rain.ja, k = 5) + s(precip.m)  <br>  Resid. Df Resid. Dev     Df  Deviance Pr(>Chi)    <br> 1    21   20.029                    <br> 2    21   20.029 1.0222e-05 3.4208e-06 6.492e-05 ***  <br> ---  <br> Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1  <br> >   <br> > AIC(logit.glm, logit.gam)  <br>         df   AIC  <br> logit.glm 4.00000 28.02893  <br> logit.gam 4.00001 28.02895  <br></code></pre>
<p>Despite the identical AIC values, the fact that the anova test is significant suggests we should use the more complex model, i.e. the GAM.</p>
<p>In the package mgcv there is also a function dedicated to the visualization of the curve on the response variable:</p>
<pre><code> vis.gam(logit.gam, view=c(&quot;rain.am&quot;, &quot;rain.ja&quot;), type=&quot;response&quot;)  <br></code></pre>
<p>this creates the following 3D plot:</p>
<div><a rel="nofollow" href="https://i0.wp.com/3.bp.blogspot.com/-k6ZWjYsPhD0/WWeYEEEF0MI/AAAAAAAAXk4/DZ3x2iSBaPwcavTt2OpYuU2EYSXeWwhogCLcBGAs/s1600/Fig10.jpeg?ssl=1" target="_blank"><img border="0" data-original-height="671" src="https://i1.wp.com/3.bp.blogspot.com/-k6ZWjYsPhD0/WWeYEEEF0MI/AAAAAAAAXk4/DZ3x2iSBaPwcavTt2OpYuU2EYSXeWwhogCLcBGAs/s640/Fig10.jpeg?resize=450%2C671&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p>This shows the response on the z axis and the two variables associated in the interaction. Since this plot is a bit difficult to interpret we can also plot is as contours:</p>
<pre><code> vis.gam(logit.gam, view=c(&quot;rain.am&quot;, &quot;rain.ja&quot;), type=&quot;response&quot;, plot.type=&quot;contour&quot;)  <br></code></pre>
<p>
<div><a rel="nofollow" href="https://i1.wp.com/2.bp.blogspot.com/-Hm51WK6txBM/WWeY2ukeYJI/AAAAAAAAXk8/dbmGRUsL5O4zOsn4eapTAODg6uMrNVnuACLcBGAs/s1600/Fig11.jpeg?ssl=1" target="_blank"><img border="0" data-original-height="880" src="https://i1.wp.com/2.bp.blogspot.com/-Hm51WK6txBM/WWeY2ukeYJI/AAAAAAAAXk8/dbmGRUsL5O4zOsn4eapTAODg6uMrNVnuACLcBGAs/s640/Fig11.jpeg?resize=450%2C880&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p>This allows to determine the changes in Leaves dependent only from the interaction between rain.am and rain.ja.</p>
<p>
<h3>Generalized Additive Mixed Effects Models</h3>
</div>
<div>In the package mgcv there is the function gamm, which allows fitting generalized additive mixed effects model, with a syntax taken from the package nlme. However, compared to what we see in the post about <a rel="nofollow" href="http://r-video-tutorial.blogspot.co.uk/2017/07/linear-mixed-effects-models-in.html" target="_blank">Mixed-Effects Models</a> there are some changes we need to make.</div>
<div>Let’s focus again on the dataset lasrosas.corn, which has a column year that we can consider as a possible source of additional random variation. The code below imports the dataset and then transform the variable year from numeric to factorial:
</div>
<div>
<pre><code> dat = lasrosas.corn  <br> dat$year = as.factor(paste(dat$year))  <br></code></pre>
<p>We will start by looking at a random intercept model. If this was not a GAM with mixed effects, but a simpler linear mixed effects model, the code to fit it would be the following:</p>
<pre><code> LME = lme(yield ~ nitro + nf + topo + bv, data=dat, random=~1|year)  <br></code></pre>
<p>This is probably the same line of code we used in the previous post. In the package nlme this same model can be fitted using a list as input for the option random. Look at the code below:</p>
<pre><code> LME1 = lme(yield ~ nitro + nf + topo + bv, data=dat, random=list(year=~1))   <br></code></pre>
<p>Here in the list we are creating a new value year, which takes a value of ~1, indicating that its random effect applies only to the intercept.<br>We can use the anova function to see that LME and LME2 are in fact the same model:</p>
<pre><code> > anova(LME, LME1)  <br>    Model df   AIC   BIC  logLik  <br> LME   1 13 27138.22 27218.05 -13556.11  <br> LME1   2 13 27138.22 27218.05 -13556.11  <br></code></pre>
<p>I showed you this alternative syntax with list because in gamm this is the only syntax we can use. So for fitting a GAM with random intercept for year we should use the following code:</p>
<pre><code> gam.ME = gamm(yield ~ nitro + nf + topo + s(bv), data=dat, random=list(year=~1))  <br></code></pre>
<p>The object gam.ME is a list with two component, a mixed effect mode and a GAM. To check their summaries we need to use two lines:</p>
<pre><code> summary(gam.ME[[1]])  <br> summary(gam.ME[[2]])  <br></code></pre>
<p>Now we can see the code to fit a random slope and intercept model. gain we need to use the syntax with a list:</p>
<pre><code> gam.ME2 = gamm(yield ~ nitro + nf + topo + s(bv), data=dat, random=list(year=~1, year=~nf))  <br></code></pre>
<p>Here we are including two random effects, one for just the intercept (year=~1) and another for random slope and intercept for each level of nf (year=~nf).</div>
	<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-video-tutorial.blogspot.com/2017/07/generalized-addictive-models-and-mixed.html"> R tutorial for Spatial Statistics</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/S33IWsso420" height="1"></a></div>