title: Aggregate Function with Variable By List
body: <p>I'm trying to create an R Script to summarize measures in a data frame. I'd like it to react dynamically to changes in the structure of the data frame. For example, I have the following block.</p>
  
  <pre><code>library(plyr) #loading plyr just to access baseball data frame
  MyData &lt;- baseball[,cbind("id","h")]
  AggHits &lt;- aggregate(x=MyData$h, by=list(MyData[,"id"]), FUN=sum)
  </code></pre>
  
  <p>This block creates a data frame (AggHits) with the total hits (h) for each player (id). Yay.</p>
  
  <p>Suppose I want to bring in the team. How do I change the by argument so that AggHits has the total hits for each combination of "id" and "team"? I tried the following and the second line throws an error: arguments must have same length</p>
  
  <pre><code>MyData &lt;- baseball[,cbind("id","team","h")]
  AggHits &lt;- aggregate(x=MyData$h, by=list(MyData[,cbind("id","team")]), FUN=sum)
  </code></pre>
  
  <p>More generally, I'd like to write the second line so that it automatically aggregates h by all variables except h. I can generate the list of variables to group by pretty easily using setdiff.</p>
  
  <pre><code># set the list of variables to summarize by as everything except hits
  SumOver &lt;- setdiff(colnames(MyData),"h")
  
  # total up all the hits - again this line throws an error
  AggHits &lt;- aggregate(x=MyData$h, by=list(MyData[,cbind(SumOver)]), FUN=sum)
  </code></pre>
  
  <p>The business purpose I'm using this for involves a csv file which has a single measure ($) and currently has about a half dozen dimensions (product, customer, state code, dates, etc.). I'd like to be able to add dimensions to the csv file without having to edit the script each time.</p>
  
  <p>I should mention that I've been able to accomplish this using ddply, but I know that using ddply to summarize a single measure is wasteful in regards to run time; aggregate is much faster.</p>
  
  <p>Thanks in advance!</p>
  
  <p>ANSWER (specific to example in question)
  Block should be</p>
  
  <pre><code>MyData &lt;- baseball[,cbind("id","team","h")]
  SumOver &lt;- setdiff(colnames(MyData),"h")
  AggHits &lt;- aggregate(x=MyData$h, by=MyData[SumOver], FUN=sum)
  </code></pre>