<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/building-formulae/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.brodrigues.co/blog/2017-12-27-build_formulae/"> Econometrics and Free Software</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://stackoverflow.com/questions/47957081/k-fold-cross-validation-in-purr-and-model" target="_blank">This</a> Stackoverflow question made me think about how to build formulae. For example, you might want to programmatically build linear model formulae and then map these models on data. For example, suppose the following (output suppressed):</p>
<pre><code>data(mtcars)

lm(mpg ~ hp, data = mtcars)
lm(mpg ~I(hp^2), data = mtcars)
lm(mpg ~I(hp^3), data = mtcars)
lm(mpg ~I(hp^4), data = mtcars)
lm(mpg ~I(hp^5), data = mtcars)
lm(mpg ~I(hp^6), data = mtcars)</code></pre>
<p>To avoid doing this, one can write a function that builds the formulae:</p>
<pre><code>create_form = function(power){
  rhs = substitute(I(hp^pow), list(pow=power))
  rlang::new_formula(quote(mpg), rhs)
}</code></pre>
<p>If you are not familiar with <code>substitute()</code>, try the following to understand what it does:</p>
<pre><code>substitute(y ~ x, list(x = 1))</code></pre>
<pre><code>## y ~ 1</code></pre>
<p>Then using <code>rlang::new_formula()</code> I build a formula by providing the left hand side, which is <code>quote(mpg)</code> here, and the right hand side, which I built using <code>substitute()</code>. Now I can create a list of formulae:</p>
<pre><code>library(tidyverse)

list_formulae = map(seq(1, 6), create_form)

str(list_formulae)</code></pre>
<pre><code>## List of 6
##  $ :Class 'formula'  language mpg ~ I(hp^1L)
##   .. ..- attr(*, &quot;.Environment&quot;)=</code></pre>