R: using ddply with a function

Viewed 653

I'm trying to use the "ddply" function in conjunction with the "summarize" function, but I'm having difficulty.

Below is an extract of my code:

  orderSubsConsolidate = ddply(merged, .(RIC,leg),summarize,fill.Quant = sum(fill.Quant),
                 fill.Price = function(merged){sum(merged[,7]*merged[,8])/sum(merged[,7})

"merged" is the matrix containing the information that I would like to summarize. I am summarizing by columns "RIC" and "leg". The problem I am having is applying a function to the fill.Price column.

This is an extract from the "merged" matrix:

Trade      RIC    leg Basket.Name Status  Order.Msg   fill.Quant  fill.Price
  ATNATNP ATNJ.J  1   ATNATNP1a1  Filled               100           200       
  ATNATNP ATNPp.J 2   ATNATNP2a1  Filled               100           200       
  ATNATNP ATNJ.J  1   ATNATNP1b1                       300           400

Essentially, what the code above is trying to do is aggregate the fill.Quant column by RIC and leg, and then populate the corresponding fill.Price column with [(fill.Price*fill.Quant)/fill.Quant], resulting in a matrix as given below:

RIC      leg  fill.Quant  fill.Price
ATNJ.J    1      400            350
ATNPp.J   2      100            350  

Any help would be greatly appreciated. Let me know if anything is unclear.

Thanks!

Mike

3 Answers

It looks like it should be

orderSubsConsolidate = ddply(merged, .(RIC,leg), summarize,
                       fill.Quant = sum(fill.Quant),
                       fill.Price = weighted.mean(fill.Price, fill.Quant))

You can also use an anonymous function:

ddply(merged, .(RIC,leg), function(x) 
                           data.frame( fill.Quant = sum(x$fill.Quant), 
                                       fill.Price = sum(x[,7]*x[,8])/sum(x[,7])))

another solution, which gives you code which is IMHO easily readable and reusable you could do:

foo <- function(quant, price){
  sum( quant*price ) / sum(price)
}

ubsConsolidate <- ddply( merged, .(RIC,leg), summarize,
  fill.Quant = sum( fill.Quant ),
  fill.Price = foo( fill.Quant, fill.Price )
)
Related