title: Call the same function by varying parameters with tidyverse and apply family functions
body: <p>This is my first question here on Stack Overflow, so I apologize in advance if I won't be clear enough.
  I searched for similar questions, but I didn't find anything (I probably didn't search enough!)</p>
  <p>Given a <code>data.frame</code> (or a<code> data.table</code> or a <code>tibble</code>) consisting of four sets of points divided into two groups:</p>
  <pre class="lang-r prettyprint-override"><code>df_points &lt;- tibble(
      x = c(rnorm(10000, mean = 0), rnorm(10000, mean = 1), 
            rnorm(10000, mean = 0), rnorm(10000, mean = 4)), 
      dist = c(rep(&quot;d1&quot;, 10000), rep(&quot;d2&quot;, 10000), 
               rep(&quot;d1&quot;, 10000), rep(&quot;d2&quot;, 10000)), 
      overlap = c(rep(&quot;o1&quot;, 20000), rep(&quot;o2&quot;, 20000))
  )
  </code></pre>
  <p>my goal is to apply the <code>density</code> function, using different values of <code>bw</code>, <code>from</code> and <code>to</code> for the <code>&quot;o1&quot;</code> and <code>&quot;o2&quot;</code> groups.</p>
  <p>I would like to solve this problem in an elegant way with both a <code>tidyverse</code> and a <code>R-base</code>-<code>data.table</code> approach (<code>apply</code> family functions).</p>
  <p>For now I have managed to do this via <code>tidyverse</code>:</p>
  <ol>
  <li><p>I define a <code>common_dens</code> function which applies <code>density</code> and returns a tibble of the <code>x</code> and <code>y</code> of the distribution</p>
  <pre class="lang-r prettyprint-override"><code>common_dens &lt;- function(df, Bw, lower, upper) {
    d &lt;- density(df, n = 2048, bw = Bw, from = lower, to = upper)
    df_d &lt;- tibble(x = d$x, y = d$y)
    return(df_d)
  }
  </code></pre>
  </li>
  <li><p>assuming that the values of upper, lower and bws are the following:</p>
  <pre class="lang-r prettyprint-override"><code>lower &lt;- c(-5.050, -4.705)
  upper &lt;- c(6.445, 9.070)
  bws &lt;- c(0.1427, 0.1417)
  </code></pre>
  <p>I get the desired dataframe through the following <code>for</code> loop:</p>
  <pre class="lang-r prettyprint-override"><code>df_dens &lt;- NULL
  for (i in 1:2) {
    df_t &lt;- df_points %&gt;% 
        filter(overlap == unique(df_points$overlap)[[i]]) %&gt;% 
        group_by(dist, overlap) %&gt;%
        summarise(common_dens(x, bws[i], lower[i], upper[i]))
    df_dens &lt;- rbind(df_dens, df_t)
  }
  </code></pre>
  </li>
  </ol>
  <p>Is there any way to remove the <code>for</code> loop?</p>
  <p>Is there a way to do the same with <code>apply</code> family functions and <code>data.table</code>?</p>
  <p>Thanks for your help!</p>