title: Sum all columns whose names start with a pattern, by group
body: <p>I'm fairly new to R and I'm trying to sum columns by groups based on their names. I have a data frame like this one:</p>
  
  <pre><code>DT &lt;- data.frame(a011=c(0,10,20,0),a012=c(010,10,0,0),a013=c(10,30,0,10),
  a021=c(10,20,20,10),a022=c(0,0,0,10),a023=c(20,0,0,0),a031=c(30,0,10,0),
  a032=c(0,0,10,0),a033=c(20,0,0,0))
  </code></pre>
  
  <p>I would like to obtain the sum of all the columns starting with "a01", of all the columns starting with "a02" and all the columns starting with "a03":</p>
  
  <pre><code>a01tot a02tot a03tot
      20     30     50
      50     20      0
      20     20     20
      10     20      0
  </code></pre>
  
  <p>So far I have used</p>
  
  <pre><code>DT$a01tot &lt;- rowSums(DT[,grep("a01", names(DT))])
  </code></pre>
  
  <p>and so on, but my real data frame has many more groups and I would like to avoid having to write a line of code for each group. I was wondering if it is possible to include "a01","a02","a03"... in a vector or list and have something that adds the columns "a01tot","a02tot","a03tot"... to the data frame automatically.</p>
  
  <p>I know that my question is very similar to this one: <a href="https://stackoverflow.com/questions/30384221/r-sum-of-rows-for-different-group-of-columns-that-start-with-similar-string">R sum of rows for different group of columns that start with similar string</a>, but the solution pointed out there,</p>
  
  <pre><code>cbind(df, t(rowsum(t(df), sub("_.*", "_t", names(df)))))
  </code></pre>
  
  <p>does not work in my case because there isn't a common element (like "_") to replace (I cannot change the names of the variables to a01_1, a02_2 etc.).</p>
  
  <p>Switching to the "long" format is not a viable solution in my case either.</p>
  
  <p>Any help will be greatly appreciated.</p>