title: Quickly apply a function multiple times in R
body: <p>I've written a function to find and save the first derivative to a png file. It takes a data.frame input and a name input and applies this to <code>filter()</code> and creates the PNG name using <code>paste0</code> then calculates and saves the first derivative.</p>
  <p>I need to apply this A LOT of times, Is there a way to apply it quickly to a vector of names? So far I've been using a hacky way, involving Excel to quickly paste down multiple columns and then merge them together, but I feel like there should be a nice way in R. I've made the data an external input for this example but as its all running off one data frame, I have just been including the data input within the actual function so that the only external input is the name... if that makes sense.</p>
  <p>The function:</p>
  <pre><code>first_deriv &lt;- function(data, site_name) {
    require(pspline)
    require(dplyr)
    png_name &lt;- paste0(site_name, &quot;.png&quot;)
    data &lt;- data %&gt;%
      filter(site == site_name) %&gt;%
      select(age, depth)
    age &lt;- data %&gt;% pull(age)
    depth &lt;- data %&gt;%  pull(depth)
    predict &lt;- predict(sm.spline(x = depth, y = age), depth, 1)
    png(filename = png_name,
        width = 600,
        height = 350)
    plot(predict, main = site_name, xlab = &quot;depth&quot;)
    dev.off()
  } 
  </code></pre>
  <p>Data example:</p>
  <pre><code>df &lt;- structure(list(site = c(&quot;4NT&quot;, &quot;4NT&quot;, &quot;4NT&quot;, &quot;4NT&quot;, &quot;4NT&quot;, &quot;10T&quot;, 
  &quot;10T&quot;, &quot;10T&quot;, &quot;10T&quot;, &quot;10T&quot;, &quot;5T&quot;, &quot;5T&quot;, &quot;5T&quot;, &quot;5T&quot;, &quot;5T&quot;), age = c(-62.1, 
  -59.7, -57.3, -54.9, -52.5, -62.4, -61.4, -60.4, -59.4, -58.4, 
  -62.3, -61.2, -60.1, -59, -57.9), depth = c(1, 2, 3, 4, 5, 1, 
  2, 3, 4, 5, 1, 2, 3, 4, 5)), row.names = c(NA, -15L), class = &quot;data.frame&quot;)
  
  names &lt;- c(&quot;10t&quot;, &quot;4NT&quot;, &quot;5T&quot;)
  </code></pre>
  <p>How it currently runs:</p>
  <pre><code>first_deriv(df, &quot;10T&quot;)
  first_deriv(df, &quot;4NT&quot;)
  first_deriv(df, &quot;5T&quot;)
  </code></pre>
  <p>Cheers,
  Paul.</p>