title: How would I group by columns with equivalent prefix and sum them?
body: <p>Let's say I have this dataframe:</p>
  <pre><code>&gt; df &lt;- data.frame(a1=c(1, 2, 3, 4, 5), b1=c(5, 4, 3, 2, 1), b2=c(10, 11, 12, 13, 14), a2=c(5, 6, 7, 8, 9), c1=c(100, 200, 300, 400, 500))
  &gt; df
    a1 b1 b2 a2  c1
  1  1  5 10  5 100
  2  2  4 11  6 200
  3  3  3 12  7 300
  4  4  2 13  8 400
  5  5  1 14  9 500
  &gt; 
  </code></pre>
  <p>As you can see, I have columns <code>a1</code> <code>a2</code> that both start with <code>a</code>, I want to sum them row-wise and generate just one column of <code>a</code>, same for column <code>b</code>. Also for <code>c</code> column, just the <code>c</code> column should stay the same as it is since there are only one column that starts with <code>c</code>.</p>
  <p>Desired output:</p>
  <pre><code>    a   b    c
  1   6  15  100
  2   8  15  200
  3  10  15  300
  4  12  15  400
  5  14  15  500
  </code></pre>
  <p>Coming from a Python, in <a href="/questions/tagged/pandas" class="post-tag" title="show questions tagged &#39;pandas&#39;" rel="tag">pandas</a> (Python Library), I could just simply use:</p>
  <pre><code>df.groupby(df.columns.str[:1], axis=1).sum()
  </code></pre>
  <p>But I am not sure how to do this in R.</p>
  <p>I tried <code>dplyr</code>:</p>
  <pre><code>df %&gt;% group_by(sub(&quot;.$&quot;, &quot;&quot;, colnames(df))) %&gt;%
    mutate(across(colnames(.), sum))
  </code></pre>
  <p>But an error popped up. New to R.</p>