<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/the-r-formula-method-the-good-parts/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://www.rstudio.com/rviews/2017/02/01/the-r-formula-method-the-good-parts/"> RStudio</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>

<p>by Max Kuhn</p>
<h1>Introduction</h1>
<p>The formula interface to symbolically specify blocks of data is ubiquitous in R. It is commonly used to generate <em>design matrices</em> for modeling function (e.g. <code>lm</code>). In traditional linear model statistics, the <em>design matrix</em> is the two-dimensional representation of the predictor set where instances of data are in rows and variable attributes are in columns (a.k.a. the <em>X</em> matrix). </p>
<p>A simple motivating example uses the inescapable iris data in a linear regression model: </p>
<p><iframe height="70px" width="1000px" src="https://beta.rstudioconnect.com/content/2474/r_formulas_block1.html"></iframe></p>
<p>While the purpose of this code chunk is to fit a linear regression models, the formula is used to specify the symbolic model as well as generating the intended design matrix. Note that the formula method defines the columns to be included in the design matrix, as well as which rows should be retained. </p>
<p>Formulas are used in R beyond specifying statistical models, and their use has been growing over time (see <a target="_blank" rel="nofollow" href="https://cran.r-project.org/web/packages/lazyeval/vignettes/lazyeval.html">this</a> or <a target="_blank" rel="nofollow" href="http://rmhogervorst.nl/cleancode/blog/2016/06/13/NSE_standard_evaluation_dplyr.html">this</a>). </p>
<p>In this post, I’ll walk through the mechanics of how some modeling functions use formulas to make a design matrix using <code>lm</code> to illustrate the details. Note, however, that the syntactical minutiae are likely to be different from function to function, even within base R. </p>
<h1>Formulas and Terms</h1>
<p><code>lm</code> initially uses the formula and the appropriate environment to translate the relationships between variables to creating a data frame containing the data. R has a fairly <a target="_blank" rel="nofollow" href="https://stat.ethz.ch/R-manual/R-devel/library/stats/html/formula.html">standard set of operators</a> that can be used to create a matrix of predictors for models. </p>
<p>We will start by looking at some of the internals of <code>lm</code> (circa December 2016).</p>
<h2>Preparing for the Model Frame</h2>
<p>The main tools used to get the design matrix are the <code>model.frame</code> and <code>model.matrix</code> functions. The definition and first few lines of <code>lm</code> are:</p>
<p><iframe height="290px" width="1000px" src="https://beta.rstudioconnect.com/content/2475/r_formulas_block2.html"></iframe></p>
<p>The goal of this code is to manipulate the formula and other arguments into an acceptable set of arguments to the <code>model.frame</code> function in the <code>stats</code> package. The code will modify the call to <code>lm</code> to use as the substrate into <code>model.frame</code>, which has many similar arguments (e.g. <code>formula</code>, <code>data</code>, <code>subset</code>, and <code>na.action</code>). However, there are arguments that are not common to both functions. </p>
<p>The object <code>mf</code> is initially created to mirror the original call. After executing <code>match.call(expand.dots = FALSE)</code>, our original call generates a value of </p>
<p><iframe height="70px" width="1000px" src="https://beta.rstudioconnect.com/content/2476/r_formulas_block3.html"></iframe></p>
<p>and <code>class(mf)</code> has a value of <code>&quot;call&quot;</code>. Note that the first element of the call, <code>mf[[1L]]</code>, has a value of <code>lm</code> with the class of <code>name</code>. </p>
<p>The next few lines remove any arguments to <code>lm</code> that are not arguments to <code>model.frame</code>, and adds another (<code>drop.unused.levels</code>). Finally, the call is modified by replacing the first element of the call (<code>lm</code>) to <code>stats::model.frame</code>. Now, <code>mf</code>, has a value of </p>
<p><iframe height="110px" width="1000px" src="https://beta.rstudioconnect.com/content/2477/r_formulas_block4.html"></iframe></p>
<h2>Creating the Model Frame and Terms</h2>
<p>When this code is executed using <code>eval(expr = mf, envir = parent.frame())</code>, the <code>model.frame</code> function returns</p>
<blockquote>
<p>A <code>data.frame</code> containing the variables used in formula plus those specified in <code>...</code>. It will have additional attributes, including “<code>terms</code>” for an object of class “<code>terms</code>” derived from <code>formula</code>, and possibly “<code>na.action</code>” giving information on the handling of <code>NA</code>s (which will not be present if no special handling was done, e.g. by <code>na.pass</code>).</p>
</blockquote>
<p>For our particular call, the first six values of <code>mf</code> are</p>
<p><iframe height="160px" width="1000px" src="https://beta.rstudioconnect.com/content/2478/r_formulas_block5.html"></iframe></p>
<p>Note that : </p>
<ul>
<li>all of the columns are present, predictors <em>and</em> response,</li>
<li>the filtering defined by the <code>subset</code> command is executed here (note the row names above),</li>
<li>the <code>Petal.Length</code> has been log transformed and the column name is not a valid name, and</li>
<li>the Species variable has not generated any dummy variables. </li>
</ul>
<p>If weights or an offset was used in the model, the resulting model frame would also include these. </p>
<p>As alluded to above, <code>mf</code> has several attributes, and includes one that would not normally be associated with a data frame (e.g. <code>&quot;terms&quot;</code>). The <code>terms</code> object contains the data that defines the relationships between variables in the formulas, as well as any transformations of the individual predictors (e.g. <code>log</code>). For our original model:</p>
<p><iframe height="520px" width="1000px" src="https://beta.rstudioconnect.com/content/2479/r_formulas_block6.html"></iframe></p>
<p>The <code>terms</code> object will be used to generate design matrices on new data (e.g. samples being predicted). </p>
<h2>Creating the Design Matrix</h2>
<p>The <code>lm</code> code has some additional steps to save the model terms and generate the design matrix: </p>
<p><iframe height="70px" width="1000px" src="https://beta.rstudioconnect.com/content/2480/r_formulas_block7.html"></iframe></p>
<p>The <code>model.matrix</code> function uses the data in the <code>terms</code> object to generate any interactions and/or dummy variables from factors. This work is mostly accomplished by a C routine. </p>
<h1>The Predictive Nature of the <code>terms</code></h1>
<p>In the previous example, the log transformation is applied to one of the columns. When using an inline function inside a formula, this transformation will be applied to the current data, as well as any future data points (say, via <code>predict.lm</code>). The same workflow is followed where a model frame is used with the <code>terms</code> object and <code>model.matrix</code>. </p>
<p>However, there are some operations that can be specified in a formula that require statistical estimates. Two examples: </p>
<ul>
<li>a <a target="_blank" rel="nofollow" href="https://en.wikipedia.org/wiki/Spline_interpolation">natural spline</a> (<code>splines::ns</code>) takes a numeric variable, does some computations, and expands that variable into multiple features that can be used to model that predictor in a nonlinear fashion.</li>
<li>orthogonal polynomials (<code>stats::poly</code>) is a basis expansion that takes a single predictor and produces new columns that correspond to the polynomial degree.</li>
</ul>
<p>As an example of natural splines: </p>
<p><iframe height="250px" width="1000px" src="https://beta.rstudioconnect.com/content/2481/r_formulas_block8.html"></iframe></p>
<p><code>ns</code> returns multiple elements: the basis function spline results (shown just above) and the data required to generate them for new data (in the attributes). </p>
<p><iframe height="550px" width="1000px" src="https://beta.rstudioconnect.com/content/2482/r_formulas_block9.html"></iframe></p>
<p>It turns out that the only statistics required to produce new spline results are the <code>knots</code>, <code>Boundary.knots</code>, and <code>intercept</code> attributes. When new data are predicted, those statistical quantities are used: </p>
<p><iframe height="210px" width="1000px" src="https://beta.rstudioconnect.com/content/2483/r_formulas_block10.html"></iframe></p>
<p>Now, getting back to formulas, we can include a function like this inline:</p>
<p><iframe height="50px" width="1000px" src="https://beta.rstudioconnect.com/content/2484/r_formulas_block11.html"></iframe></p>
<p>The resulting <code>terms</code> object saves the model specification, and also the values required to reproduce the spline basis function. The <code>terms</code> object contains an attribute that is misleadingly named <code>predvars</code> that has this information: </p>
<p><iframe height="240px" width="1000px" src="https://beta.rstudioconnect.com/content/2485/r_formulas_block12.html"></iframe></p>
<p>When <code>predict.lm</code> is invoked with a new data set, the terms are passed to <code>model.frame</code> and the <code>predvars</code> are evaluated on the new data, e.g.,</p>
<p><iframe height="410px" width="1000px" src="https://beta.rstudioconnect.com/content/2486/r_formulas_block13.html"></iframe></p>
<p>In summary, R’s formula interface works by exploiting the original formula as a general expression, and the <code>terms</code> object is where most of the information about the design matrix is stored. </p>
<p>Finally, it is possible to include more complex operations in the formula. For example, two techniques for imputation in predictive models are using tree ensembles and <em>K</em>-nearest neighbors. In each case, a model can be created to impute a predictor, and this model also could be embedded into <code>predvars</code> as long as the prediction function can be exploited as an expression. </p>
<p>There are some severe limitations to formulas which may not be obvious and various packages have had to work around these issues. The second post on formulas (“The Bad”) will illustrate these shortcomings. </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://www.rstudio.com/rviews/2017/02/01/the-r-formula-method-the-good-parts/"> RStudio</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/i3A9gk_Erp0"></a></div>