title: Aggregating rows for multiple columns in R
body: <p>I have a df that basically looks like this:</p>
  
  <pre><code>Id  A    B    C total
  3   5    0    1  6
  3   4    3    4   11
  3   2    1    2    5
  4   5    4    3   12
  4   3    2    4    9
  4   1    1    1    3
  </code></pre>
  
  <p>I want to collapse the rows by Id and get:</p>
  
  <pre><code>Id   A    B    C    total
  3    11   4    7     22
  4    9    7    8   24
  </code></pre>
  
  <p>I was able to do so for one column with:</p>
  
  <pre><code>df.grouped&lt;- aggregate(df$A~Id, data=df, FUN="sum")
  </code></pre>
  
  <p>I have many columns (A-Z), so I need some kind of loop. I tried:</p>
  
  <pre><code>df.grouped&lt;- aggregate(df[4:51]~Id, data=df, FUN="sum")
  names(df.grouped)&lt;-paste(names(df)[4:51])
  </code></pre>
  
  <p>But got:</p>
  
  <pre><code>Error in model.frame.default(formula = df[4:51] ~ Id, data = df) : 
  invalid type (list) for variable 'df[4:51]'
  </code></pre>
  
  <p>As you can see, I also want the names in df.grouped to be the same as in df.</p>
  
  <p>Any ideas will be very helpful</p>
  
  <p>Thanks</p>