title: Apply function to subset of columns using purrr and dplyr
body: <p>I am new to the <code>purrr</code> package, but I like the little I know about it.</p>
  <p>Using only tidyverse packages, I would like to be able to add a column that is the result of a function applied to a subset of columns in a dataset.</p>
  <p>Here is some toy data. A series of columns of factors</p>
  <pre><code>df &lt;- data.frame(a_1 = factor(rep(letters[1:3], times = 5)),
                   a_2 = factor(rep(letters[1:3], times = 5)),
                   a_3 = factor(rep(letters[1:3], times = 5)),
                   b_1 = factor(rep(letters[1:3], times = 5)),
                   b_2 = factor(rep(letters[1:3], times = 5)),
                   b_3 = factor(rep(letters[1:3], times = 5)))
  
  df
  
  # output
  #  a_1 a_2 a_3 b_1 b_2 b_3
  # 1    a   a   a   a   a   a
  # 2    b   b   b   b   b   b
  # 3    c   c   c   c   c   c
  # 4    a   a   a   a   a   a
  # 5    b   b   b   b   b   b
  # 6    c   c   c   c   c   c
  # 7    a   a   a   a   a   a
  # 8    b   b   b   b   b   b
  # 9    c   c   c   c   c   c
  # 10   a   a   a   a   a   a
  # 11   b   b   b   b   b   b
  # 12   c   c   c   c   c   c
  # 13   a   a   a   a   a   a
  # 14   b   b   b   b   b   b
  # 15   c   c   c   c   c   c
  </code></pre>
  <p>The following function, via <code>purr::map_df</code> and <code>dplyr::select</code> cycles through the columns of df that start with <code>a_</code>, converts them to numeric class, finds the mean of those columns, then multiplies by 3.</p>
  <pre><code>rowMeans(purrr::map_df(.x = df %&gt;% dplyr::select(grep(&quot;a_&quot;, names(.))),
                         .f = function(x) x &lt;- as.numeric(x))*3)
  
  # output
  # [1] 3 6 9 3 6 9 3 6 9 3 6 9 3 6 9
  </code></pre>
  <p>This is the correct output, but is a vector.</p>
  <p><strong>Using a tidyverse function how do I add the result of my function to the existing</strong> <code>df</code> <strong>dataset as a new column, instead of as a vector?</strong></p>
  <p>Something involving <code>dplyr::mutate</code> I assume, but I can't work it out.</p>