Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R data frame: add values in common rows

Tags:

list

dataframe

r

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..

like image 367
Dinoop Nair Avatar asked May 25 '26 15:05

Dinoop Nair


2 Answers

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.

like image 190
juba Avatar answered May 28 '26 05:05

juba


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....

like image 21
A5C1D2H2I1M1N2O1R2T1 Avatar answered May 28 '26 04:05

A5C1D2H2I1M1N2O1R2T1