<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/r-tip-how-to-pass-a-formula-to-lm/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.win-vector.com/blog/2018/09/r-tip-how-to-pass-a-formula-to-lm/"> R – Win-Vector Blog</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p><a rel="nofollow" href="https://www.r-project.org/" target="_blank"><code>R</code></a> <a rel="nofollow" href="http://www.win-vector.com/blog/tag/r-tips/" target="_blank">tip</a> : how to pass a <code>formula</code> to <code>lm()</code>.</p>
<p>Often when modeling in <a rel="nofollow" href="https://www.r-project.org/" target="_blank"><code>R</code></a> one wants to build up a formula outside of the modeling call. This allows the set of columns being used to be passed around as a vector of strings, and treated as data. Being able to treat controls (such as the set of variables to use) as manipulable values allows for very powerful automated modeling methods.</p>
<p><span></span></p>
<p>
<p>What we are talking about is the ability to take the outcome (or dependent variable) and modeling variables (or independent variables) from somewhere else, as data. The kind of code we are talking about is shown below.</p>
<p><code>
<pre>
# specifications of how to model,
# coming from somewhere else
outcome &lt;- &quot;mpg&quot;
variables &lt;- c(&quot;cyl&quot;, &quot;disp&quot;, &quot;hp&quot;, &quot;carb&quot;)

# our modeling effort, 
# fully parameterized!
f &lt;- as.formula(
  paste(outcome, 
        paste(variables, collapse = &quot; + &quot;), 
        sep = &quot; ~ &quot;))
print(f)
# mpg ~ cyl + disp + hp + carb

model &lt;- lm(f, data = mtcars)
print(model)

# Call:
#   lm(formula = f, data = mtcars)
# 
# Coefficients:
#   (Intercept)          cyl         disp           hp         carb  
#     34.021595    -1.048523    -0.026906     0.009349    -0.926863  
</pre>
<p></p>
<p>This works, and the <code>paste()</code> pattern is so useful we suggest researching and memorizing it.</p>
<p>However the “call” portion of the model is reported as “<code>formula = f</code>” (the name of the variable carrying the formula) instead of something more detailed. Frankly this printing issue never bothered us. None of our tools or workflows currently use the model <code>call</code> item, and for a very large number of variables formatting the call contents in the model report becomes unweildy. We also already have the formula in a variable, so if we need it we can save it or pass it along.</p>
<p>There is a much better place on many models to get model structure information from than the model <code>call</code> item: the model <code>terms</code> item. This item carries a lot of information and formats up quite nicely:</p>
<p><code>
<pre>
format(terms(model))
# [1] &quot;mpg ~ cyl + disp + hp + carb&quot;
</pre>
<p></p>
<p>Notice we used accessor notation (<code>terms(model)</code>) to get the information. List notation, such as <code>model$terms</code> also works.</p>
<p>In addition, as is so often the case in <code>R</code>, there is already a known solution to the above problem. For common <code>R</code> issues one should suspect there is a good available <code>R</code> solution. It is just a matter of finding the right reference or teaching. For example: to control the <code>model$call</code> item use the <code>bquote()</code> facility, as we show below.</p>
<p><code>
<pre>
outcome &lt;- &quot;mpg&quot;
variables &lt;- c(&quot;cyl&quot;, &quot;disp&quot;, &quot;hp&quot;, &quot;carb&quot;)

f &lt;- as.formula(
  paste(outcome, 
        paste(variables, collapse = &quot; + &quot;), 
        sep = &quot; ~ &quot;))
print(f)
# mpg ~ cyl + disp + hp + carb


# The new line of code
model &lt;- eval(bquote(   lm(.(f), data = mtcars)   ))



print(model)
# Call:
#   lm(formula = mpg ~ cyl + disp + hp + carb, data = mtcars)
# 
# Coefficients:
#   (Intercept)          cyl         disp           hp         carb  
#     34.021595    -1.048523    -0.026906     0.009349    -0.926863  
</pre>
<p></p>
<p><code>base::bquote()</code> is a very sensible implementation of quasi-quotation or the Lisp backquote facility. The idea is everything inside the <code>bquote()</code> is “quoted” (held unevaluated as an <code>R</code>-language tree, not as mere strings!), with the exception of anything marked with the “<code>.()</code>” notation. Anything marked with <code>.()</code> is not quoted, but substituted in by value. This is why we see the contents of our formula, and not the name of the variable we used to denote it. <code>base::eval()</code> is finally used to execute the combined contents.</p>
<p><code>base::bquote()</code> has some deliberate limits (unwillingness to substitute into left-hand-sides of <code>=</code>-expressions, and some complexity of notation), which is why we promote <a rel="nofollow" href="https://cran.r-project.org/web/packages/wrapr/vignettes/let.html" target="_blank"><code>wrapr::let()</code></a> for name for name replacement tasks (<code>wrapr::let()</code> is for substituting a <em>fixed</em> number of symbols and combines the <code>eval(bquote())</code> pattern into a single function).</p>
<p>In conclusion: the exact <em>saved</em> call-text in a model object may not be important, as a better structured record of the model specification is found in the model <code>terms</code> item. However, you can also control the model call text by evaluating the model using the <code>eval()</code>/<code>bquote()</code>/<code>.()</code> pattern we demonstrated above.</p>

				
		
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://www.win-vector.com/blog/2018/09/r-tip-how-to-pass-a-formula-to-lm/"> R – Win-Vector Blog</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 width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/Kuh74DzaOu4" height="1"></a></div></code></code></code>