I have a data frame like this .
> df1
portfolio date ticker quantity price
1 port 2010-01-01 AAPL 100 10
2 port 2010-01-01 AAPL 200 10
3 port 2010-01-01 AAPL 400 11
If the rows of df1 except quantity are same, then add the quantity of common rows.
I mean, i need the following output
portfolio date ticker quantity price
1 port 2010-01-01 AAPL 300 10
3 port 2010-01-01 AAPL 400 11
How can i do that? Thanks..
Here you go... :-)
For plyr :
ddply(df, .(portfolio, date, ticker, price),summarize, quantity=sum(quantity))
For data.table :
dt <- data.table(df)
dt[,list(quantity=sum(quantity)),by=list(portfolio,date,ticker,price)]
There may be a more concise way to express the list of grouping variables. Otherwise, the aggregate solution is much more elegant.
Use aggregate. Assuming your data.frame is called "mydf":
> aggregate(quantity ~ ., mydf, sum)
portfolio date ticker price quantity
1 port 2010-01-01 AAPL 10 300
2 port 2010-01-01 AAPL 11 400
Of course, we should all now wait for the data.table and ddply versions to populate the answers list....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With