title: How to merge and create subsets in a for loop (R)?
body: <p>I want to optimize this code in a for loop for a bigger set of data. </p>
  
  <pre><code>library(reshape2)
  Customer&lt;- c("Susan","Louis", "Frank","Susan")
  Seller&lt;- c("Ivan", "Donald","Chris","Ivan")
  Service&lt;-c("COU","CAR", "FCL","CAR")
  Billingmean&lt;- c(100,200,300,400)
  WrsHoldSum&lt;-c(0,0,0,0)
  Group&lt;- c("n1","n2"," "," ")
  B1&lt;- c(0,2,2,1) 
  B2&lt;-c(9,8,7,6)
  B3&lt;- c(5,4,3,2)
  df&lt;- data.frame(Customer, Seller,Service, Billingmean,WrsHoldSum, Group,B1,B2,B3)
  sub1&lt;- dcast(data= df, formula= Customer+Group+Seller+WrsHoldSum~Service,fun.aggregate= sum,value.var= "Billingmean")
  sub2&lt;- dcast(data= df, formula= Customer+Group+Seller+WrsHoldSum~Service,fun.aggregate= sum,value.var= "B1") 
  sub3&lt;- dcast(data= df, formula= Customer+Group+Seller+WrsHoldSum~Service,fun.aggregate= sum,value.var= "B2")
  sub4&lt;- dcast(data= df, formula= Customer+Group+Seller+WrsHoldSum~Service,fun.aggregate= sum,value.var= "B3")
  
  finaldf&lt;- merge (sub1,sub2, sub3, sub4,by=c("Customer","Group","Seller","WrsHoldSum"))
  </code></pre>