<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/functional-peace-of-mind/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.brodrigues.co/blog/2017-11-14-peace_r/"> Econometrics and Free Software</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>I think what I enjoy the most about functional programming is the peace of mind that comes with it. With functional programming, there’s a lot of stuff you don’t need to think about. You can write functions that are general enough so that they solve a variety of problems. For example, imagine for a second that R does not have the <code>sum()</code> function anymore. If you want to compute the sum of, say, the first 100 integers, you could write a loop that would do that for you:</p>
<pre><code>numbers = 0

for (i in 1:100){
  numbers = numbers + i
}

print(numbers)</code></pre>
<pre><code>## [1] 5050</code></pre>
<p>The problem with this approach, is that you cannot reuse any of the code there, even if you put it inside a function. For instance, what if you want to merge 4 datasets together? You would need something like this:</p>
<pre><code>library(dplyr)
data(mtcars)</code></pre>
<pre><code>mtcars1 = mtcars %>%
  mutate(id = &quot;1&quot;)

mtcars2 = mtcars %>%
  mutate(id = &quot;2&quot;)

mtcars3 = mtcars %>%
  mutate(id = &quot;3&quot;)

mtcars4 = mtcars %>%
  mutate(id = &quot;4&quot;)

datasets = list(mtcars1, mtcars2, mtcars3, mtcars4)

temp = datasets[[1]]

for(i in 1:3){
  temp = full_join(temp, datasets[[i+1]])
}</code></pre>
<pre><code>## Joining, by = c(&quot;mpg&quot;, &quot;cyl&quot;, &quot;disp&quot;, &quot;hp&quot;, &quot;drat&quot;, &quot;wt&quot;, &quot;qsec&quot;, &quot;vs&quot;, &quot;am&quot;, &quot;gear&quot;, &quot;carb&quot;, &quot;id&quot;)
## Joining, by = c(&quot;mpg&quot;, &quot;cyl&quot;, &quot;disp&quot;, &quot;hp&quot;, &quot;drat&quot;, &quot;wt&quot;, &quot;qsec&quot;, &quot;vs&quot;, &quot;am&quot;, &quot;gear&quot;, &quot;carb&quot;, &quot;id&quot;)
## Joining, by = c(&quot;mpg&quot;, &quot;cyl&quot;, &quot;disp&quot;, &quot;hp&quot;, &quot;drat&quot;, &quot;wt&quot;, &quot;qsec&quot;, &quot;vs&quot;, &quot;am&quot;, &quot;gear&quot;, &quot;carb&quot;, &quot;id&quot;)</code></pre>
<pre><code>glimpse(temp)</code></pre>
<pre><code>## Observations: 128
## Variables: 12
## $ mpg  </code></pre>