title: Applying a Magrittr Pipe in lapply() with R
body: <p>I would like to find a way to implement a series of piped functions through an lapply statement and generate multiple databases as a result. Here is a sample data set:</p>
  
  <pre><code># the data
  d &lt;- tibble(
    categorical = c("a", "d", "b", "c", "a", "b", "d", "c"),
    var_1 = c(0, 0, 1, 1, 1, 0, 1, 0),
    var_2 = c(0, 1, 0, 0, 0, 0 ,1, 1),
    var_3 = c(0, 0, 1, 1, 1, 1, 1, 1),
    var_4 = c(0, 1, 0, 1, 0, 0, 0, 0)
  )
  </code></pre>
  
  <p>Here is the outcome I want:</p>
  
  <pre><code>$var_1
  a  b  c  d
  1  1  1  1
  
  $var_2
  a  b  c  d
  0  0  1  2
  
  $var_3
  a  b  c  d
  1  2  2  1
  
  $var_4
  a  b  c  d
  0  0  1  1
  </code></pre>
  
  <p>I can recreate each list element individually with ease. Here is my sample code with dplyr:</p>
  
  <pre><code>d %&gt;%
    filter(var_1 == 1) %&gt;%
    group_by(categorical, var_1) %&gt;%
    summarise(n = n()) %&gt;%
    select(-var_1) %&gt;%
    rename("var_1" = "n") %&gt;%
    ungroup() %&gt;%
    spread(categorical, var_1)
  
  # A tibble: 1 x 4
        a     b     c     d
    &lt;int&gt; &lt;int&gt; &lt;int&gt; &lt;int&gt;
  1     1     1     1     1
  </code></pre>
  
  <p>But, I want to automate the process across all columns and create an object that contains each row of information as a list.</p>
  
  <p>Here is where I started:</p>
  
  <pre><code>lapply(d[,2:5], function (x) d %&gt;%
    filter(x == 1) %&gt;%
    group_by(categorical, x) %&gt;%
    summarise(n = n()) %&gt;%
    select(-x) %&gt;%
    rename("x" = "n") %&gt;%
    ungroup() %&gt;%
    spread(categorical, x))
  </code></pre>
  
  <p>Any help would be much appreciated!</p>