<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/raccoon-ch-1-introduction-to-linear-models-with-r/"></div></div><div><a data-url="https://www.r-bloggers.com/raccoon-ch-1-introduction-to-linear-models-with-r/" data-counturl="https://www.r-bloggers.com/raccoon-ch-1-introduction-to-linear-models-with-r/" data-count="horizontal" data-text="Raccoon | Ch. 1 – Introduction to Linear Models with R" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.quantide.com/raccoon-ch-1-introduction-to-linear-models-with-r/"> R blog | Quantide - R training &amp; consulting</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<div>
<div>
<div>
<div>
<div>
<p><em>This article is the first chapter of Quantide’s web book “<a target="_blank" href="http://www.quantide.com/raccoon-statistical-models-with-r-web-book/">Raccoon – Statistical Models with R</a>“. Raccoon is Quantide’s third web book after “<a target="_blank" href="http://www.quantide.com/rabbit-introduction-to-r/">Rabbit – Introduction to R</a>” and “<a target="_blank" href="http://www.quantide.com/ramarro-r-for-developers/">Ramarro – R for Developers</a>“. See the <a target="_blank" href="http://www.quantide.com/raccoon-statistical-models-r-free-web-book/">full project here</a>.</em></p>
<p><em>This chapter is an introduction to the first section of the book, Linear Models, and contain some theoretical explanation and lots of examples. At the end of the chapter you will find two summary tables with </em><span>Linear model formulae and functions in R</span> <em>and </em><span>Common R functions for inference</span>.</p>
<p> </p>
<h2>Introduction to Linear Models</h2>
</div>
<pre>require(ggplot2)
require(qdata)
require(dplyr)</pre>
<p>Let us consider a simple relation between height and weight in a sample of young people:
<pre>data(ds)
str(ds)</pre>
<pre>## Classes 'tbl_df', 'tbl' and 'data.frame':    200 obs. of  3 variables:
##  $ height: num  152 152 172 159 171 ...
##  $ weight: num  54.5 62.6 61.4 62.9 64.5 ...
##  $ gender: Factor w/ 2 levels &quot;F&quot;,&quot;M&quot;: 1 1 1 1 1 1 1 1 1 1 ...</pre>
<pre>head(ds)</pre>
<pre>## # A tibble: 6 × 3
##     height   weight gender
##           
## 1 152.4451 54.45182      F
## 2 152.3823 62.56590      F
## 3 172.2429 61.43563      F
## 4 158.9386 62.93164      F
## 5 170.7935 64.51634      F
## 6 183.1107 74.17911      F</pre>
<p>Each row of above fictitious <code>ds</code> dataframe contains height (in cm) weight (in Kg), and gender of a different young person.<br>
Now, one might want to find a simple (or <strong>smooth</strong>) numerical relation (a <strong>regression</strong>) between <code>height</code> and <code>weight</code> measures, where <code>weight</code> will depend on <code>height</code>.
<pre>ggp &lt;- ggplot(data=ds,mapping = aes(x=height, y=weight)) +
  geom_point(colour=&quot;darkblue&quot;) +
  xlab(&quot;Height&quot;) + ylab(&quot;Weight&quot;) + 
  ggtitle(&quot;Plot of Weight Vs. Height in 200 young people&quot;)

print(ggp)</pre>
<div>
<p><img sizes="(max-width: 451px) 100vw, 451px" alt="immagine-1-introduction-001" class="wp-image-2830" src="https://i0.wp.com/www.quantide.com/wp-content/uploads/2016/09/Immagine-1-Introduction-001-300x300.png?resize=451%2C451" data-recalc-dims="1"></p>
<p>Relation between Weight and Height of 200 young people</p>
</div>
<p>In other words, one might want to draw a smooth line that “best approximates” the causal relation between <code>height</code> and <code>weight</code> (i.e., the height influences the weight).</p>
<p>Note that the relation might be really simple, as finding a simple “central value” (i.e., when one hypotesizes that <code>weight</code> does not change when varying the height); in this case the “best” smooth line could be the mean of <code>weight</code> values)</p>
<pre>ds2 &lt;- ds %>% slice(c(1,1:20*10))
ds2 &lt;- ds2 %>% mutate(x1=height, x0=height, y0=weight, y1=mean(weight))

ggp &lt;- ggplot(data=ds,mapping = aes(x=height, y=weight)) +
  geom_point(colour=&quot;darkblue&quot;) +
  geom_hline(yintercept = mean(ds$weight), colour=&quot;red&quot;) +
  geom_segment(data=ds2,mapping = aes(x=x0, xend=x1, y=y0, yend=y1), colour=&quot;green&quot;, linetype=2) +
  xlab(&quot;Height&quot;) + ylab(&quot;Weight&quot;) + 
  ggtitle(&quot;Plot of Weight Vs. Height in 200 young people&quot;)

print(ggp)</pre>
<div>
<p><img sizes="(max-width: 451px) 100vw, 451px" alt="immagine-2-introduction-001" class="wp-image-2831" src="https://i2.wp.com/www.quantide.com/wp-content/uploads/2016/09/Immagine-2-Introduction-001-300x300.png?resize=451%2C451" data-recalc-dims="1"></p>
<p>Relation between Weight and Height in 200 young people with ‘best constant model’ or the relation might be a few more complex, as a straight line of type (see next graph):</p>
</div>
<p><span> y=\(\beta_0\)+ \(\beta_1\)\( \cdot x \)</span></p>
<pre>ds1 &lt;- ds %>% arrange(height)
md &lt;- lm(weight~height*gender,data=ds1)
ds2 &lt;- ds2 %>% mutate(y1=predict(md,newdata=ds2))

ggp &lt;- ggplot(data=ds,mapping = aes(x=height, y=weight)) +
  geom_point(colour=&quot;darkblue&quot;) +
  geom_smooth(method = &quot;lm&quot;,se = FALSE, colour=&quot;red&quot;) + 
  geom_segment(data=ds2,mapping = aes(x=x0, xend=x1, y=y0, yend=y1), colour=&quot;green&quot;, linetype=2) +
  xlab(&quot;Height&quot;) + ylab(&quot;Weight&quot;) + 
  ggtitle(&quot;Plot of Weight Vs. Height in 200 young people&quot;)

print(ggp)</pre>
<div>
<p><img sizes="(max-width: 451px) 100vw, 451px" alt="immagine-3-introduction-001" class="wp-image-2832" src="https://i1.wp.com/www.quantide.com/wp-content/uploads/2016/09/Immagine-3-Introduction-001-300x300.png?resize=451%2C451" data-recalc-dims="1"></p>
<div>
<p>Relation between Weight and Height in 200 young people with best straight line model or also more complex.</p>
</div>
<p>Anyway, in either above cases the line is estimated by using the so-called “least squares” method: the “best” line is the one for which the sum of squares of differences between the points and line itself is minimum.</p>
<p><span>In first model, the “level” for which one can obtain the minimum of sum of squares of distance of points from line is at the average of weight values \((\overline{y}\)). The dashed green lines represent the distances of some observed points from the “best” (estimated) line.</span></p>
<p>In second model, the result of application of least-squares method is a few more complex, but can be obtained in closed form, as:</p>
<p><img sizes="(max-width: 300px) 100vw, 300px" alt="formula" class="wp-image-3038" src="https://i2.wp.com/www.quantide.com/wp-content/uploads/2016/10/Formula-300x100.png?resize=300%2C100" data-recalc-dims="1"></p>
<p>where \(\hat\beta_0\) and \(\hat\beta_1\) represent, respectively, the estimates of \(\beta_0\) and \(\beta_1\), \(n\) is the number of people in sample (the sample size), and \(\overline{x}\) and \(\overline{y}\) represent, respectively, the arithmetic mean of height and the arithmetic mean of weight values.</p>
<p>The least-squares method may be seen as a particular case of the more general <strong>Maximum Likelihood</strong> method to data for which the Normality assumption may be applied (see “Some theory on Linear Models” chapter).</p>
</div>
<p>However notice that least-squares method by itself does not give information about the “better” model: in above examples, least-squares estimates are available for the “only-mean” model as well as for the straight line model, but no information about the preferable model is returned by the least-squares. Some tests can be used to choose the best model (in next chapters we will give information about that).</p>
<p>Finally, the relation can be more complex again: for example, a different line for male and female people may be estimated (see next Figure).</p>
<pre>ggp &lt;- ggplot(data=ds,mapping = aes(x=height, y=weight, colour=gender)) +
  geom_point() +
  geom_smooth(mapping = aes(colour=gender), method = &quot;lm&quot;,se = FALSE ) + 
  geom_segment(data=ds2,mapping = aes(x=x0, xend=x1, y=y0, yend=y1), colour=&quot;green&quot;, linetype=2) +
  xlab(&quot;Height&quot;) + ylab(&quot;Weight&quot;) + 
  ggtitle(&quot;Plot of Weight Vs. Height in 200 young people&quot;)+
  theme(legend.position=&quot;top&quot;)

print(ggp)</pre>
<p>
<img sizes="(max-width: 451px) 100vw, 451px" alt="immagine-4-introduction" class="wp-image-2833" src="https://i0.wp.com/www.quantide.com/wp-content/uploads/2016/09/Immagine-4-Introduction-300x300.png?resize=451%2C451" data-recalc-dims="1"></p>
<div>
<p>Relation between Weight and Height in 100 male and 100 female young people</p>
</div>
<p>This is because, roughly speaking, a model is said a <strong>linear model</strong> if unknown parameters and error term combine linearly, and not necessarily if the functional form, or relation, between independent and dependent variables is linear. In “Some Theory on Linear Model” chapter this topic is covered more thoroughly.</p>
<div>
<h2>Linear model formulae and functions in R</h2>
<p>There are lots of different types of regression models in statistics but R mantains a coherent syntax for the estimation of all of them. Indeed, the common interface to fit a model in R is made of a call to the corresponding function with arguments <code>formula</code> and <code>data</code>.</p>
<p>Talking about linear regression models, the <code>lm</code> and <code>aov</code> functions are used in R to fit respectively linear regression and analysis of variance model and their syntax is:</p>
<pre>linear_model &lt;- lm(formula, data)
anova_model &lt;- aov(formula, data)</pre>
<p>
<code>formula</code> argument is a symbolic description of the model to be fitted, which has the form: <code>response variable ∼ predictor variables</code>. The variables involved in <code>formula</code> should be columns of a dataframe specied in <code>data</code> argument.</p>
<p>For example, consider <code>ds</code> dataset.</p>
<pre>str(ds)</pre>

<pre>## Classes 'tbl_df', 'tbl' and 'data.frame':    200 obs. of  3 variables:
##  $ height: num  152 152 172 159 171 ...
##  $ weight: num  54.5 62.6 61.4 62.9 64.5 ...
##  $ gender: Factor w/ 2 levels &quot;F&quot;,&quot;M&quot;: 1 1 1 1 1 1 1 1 1 1 ...</pre>
<p>
To fit a linear model on the relation between <code>weight</code> and <code>height</code> of <code>ds</code> dataset, the sintax is:</p>
<pre>linear_model &lt;- lm(formula = weight ~ height, data = ds)</pre>
<p>
In the following table some formulas examples are shown, where <code>y</code> represents the response variable, <code>x</code>, <code>x1</code>, <code>x2</code>, <code>x3</code> represent continuous variates, whereas upper case letters represent factors:</p>
<table>
<thead>
<tr>
<th align="left"><strong>Expression</strong></th>
<th align="left"><strong>Description</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td align="left"><code>y ~ x</code></td>
<td align="left">Simple regression</td>
</tr>
<tr>
<td align="left"><code>y ~ 1 + x</code></td>
<td align="left">Explicit intercept</td>
</tr>
<tr>
<td align="left"><code>y ~ -1 + x</code></td>
<td align="left">Through the origin</td>
</tr>
<tr>
<td align="left"><code>y ~ x + I(x^2)</code></td>
<td align="left">Quadratic regression</td>
</tr>
<tr>
<td align="left"><code>y ~ x1 + x2 + x3</code></td>
<td align="left">Multiple regression</td>
</tr>
<tr>
<td align="left"><code>y ~ G + x1 + x2</code></td>
<td align="left">Parallel regressions</td>
</tr>
<tr>
<td align="left"><code>y ~ G / (x1 + x2)</code></td>
<td align="left">Separate regressions</td>
</tr>
<tr>
<td align="left"><code>sqrt(y) ~ x + I(x^2)</code></td>
<td align="left">Transformed</td>
</tr>
<tr>
<td align="left"><code>y ~ G</code></td>
<td align="left">Single classification</td>
</tr>
<tr>
<td align="left"><code>y ~ A + B</code></td>
<td align="left">Randomized block</td>
</tr>
<tr>
<td align="left"><code>y ~ B + N * P</code></td>
<td align="left">Factorial in blocks</td>
</tr>
<tr>
<td align="left"><code>y ~ x + B + N * P</code></td>
<td align="left">with covariate</td>
</tr>
<tr>
<td align="left"><code>y ~ . -x1</code></td>
<td align="left">All variables except <code>x1</code></td>
</tr>
<tr>
<td align="left"><code>y ~ . + A:B</code></td>
<td align="left">Add interaction (<code>update</code>)</td>
</tr>
<tr>
<td align="left"><code>Nitrogen ~ Times*(River/Site)</code></td>
<td align="left">More complex design</td>
</tr>
</tbody>
</table>
<p>The items in <em>Expression</em> column show several examples of formulas.<br>
An expression of the form <code>y ~</code> <code>model</code> is interpreted as a specification that the response <code>y</code> is modelled by a linear predictor specified symbolically by <code>model</code>. Such a model consists of a series of terms separated by <code>+</code> operators.</p>
<p>In next chapters, many examples of use of these functions will be then presented.</p>
<h3>Common R functions for inference</h3>
<p>In following table the main functions used for linear model analysis are presented.</p>
<p>All the functions have to be applied on objects of class <code>lm</code> or class <code>aov</code>, obtained by calling, respectively,</p>
<p><code>obj &lt;- lm(formula)</code> or <code>obj &lt;- aov(formula)</code></p>
<table>
<thead>
<tr>
<th align="left"><strong>Expression</strong></th>
<th align="left"><strong>Description</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td align="left"><code>coef(obj)</code></td>
<td align="left">regression coefficients</td>
</tr>
<tr>
<td align="left"><code>resid(obj)</code></td>
<td align="left">residuals</td>
</tr>
<tr>
<td align="left"><code>fitted(obj)</code></td>
<td align="left">fitted values</td>
</tr>
<tr>
<td align="left"><code>summary(obj)</code></td>
<td align="left">analysis summary</td>
</tr>
<tr>
<td align="left"><code>predict(obj, newdata = ndat)</code></td>
<td align="left">predict for newdata</td>
</tr>
<tr>
<td align="left"><code>deviance(obj)</code></td>
<td align="left">residual sum of squares</td>
</tr>
</tbody>
</table>
</div></div>
<p> 
</div>
<p> </p></div>
<p> </p></div>
<p> 
<p>The post <a target="_blank" rel="nofollow" href="http://www.quantide.com/raccoon-ch-1-introduction-to-linear-models-with-r/">Raccoon | Ch. 1 – Introduction to Linear Models with R</a> appeared first on <a target="_blank" rel="nofollow" href="http://www.quantide.com/">Quantide – R training &amp; consulting</a>.</p>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="https://www.r-bloggers.com/raccoon-ch-1-introduction-to-linear-models-with-r/"></div></div><div><a data-url="https://www.r-bloggers.com/raccoon-ch-1-introduction-to-linear-models-with-r/" data-counturl="https://www.r-bloggers.com/raccoon-ch-1-introduction-to-linear-models-with-r/" data-count="vertical" data-text="Raccoon | Ch. 1 – Introduction to Linear Models with R" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://www.quantide.com/raccoon-ch-1-introduction-to-linear-models-with-r/"> R blog | Quantide - R training &amp; consulting</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/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/?s=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/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/23fbsS7AOvo"></a></div>