Reputation: 7608
I'm currently working on a data.table (myDT) with the folowing 3 columns :
TRADE_DATE TRADER VOLUME
01-MAY-2013 T1 100
01-MAY-2013 T2 200
01-MAY-2013 T3 500
01-MAY-2013 T4 200
02-MAY-2013 T1 400
02-MAY-2013 T2 500
02-MAY-2013 T3 50
02-MAY-2013 T4 50
I would like to find a way to calculate a share volume per trader per day. Currently I'm calculating the total volume per day then merge with the previous table to calculate the market share of each trader per day. Is there a more straightforward way to do it with data.tables ?
I attached herunder my code :
daylyVolume<-myDT[,list(DAILY_VOLUME=sum(VOLUME)),by="TRADE_DATE"]
myDT<-merge(myDT,daylyVolume,all=TRUE,by='TRADE_DATE')
myDT$"SHARE_VOLUME"<-100*myDT$"VOLUME"/myDT$"DAILY_VOLUME"
The result is the following:
TRADE_DATE TRADER VOLUME SHARE DAYLY_VOLUME
01-MAY-2013 T1 100 10 1000
01-MAY-2013 T2 200 20 1000
01-MAY-2013 T3 500 50 1000
01-MAY-2013 T4 200 20 1000
02-MAY-2013 T1 400 40 1000
02-MAY-2013 T2 500 50 1000
02-MAY-2013 T3 50 5 1000
02-MAY-2013 T4 50 5 1000
Upvotes: 2
Views: 1622
Reputation: 6197
Do you want this?
myDT[,list(share= VOLUME/sum(VOLUME)*100),by="TRADE_DATE"]
Upvotes: 1
Reputation: 49033
A simple way is to do this :
dt[,list(VOLUME,DAILY_VOLUME=sum(VOLUME),SHARE=VOLUME/sum(VOLUME)*100),by="TRADE_DATE"]
TRADE_DATE VOLUME DAILY_VOLUME SHARE
1: 01-MAY-2013 100 1000 10
2: 01-MAY-2013 200 1000 20
3: 01-MAY-2013 500 1000 50
4: 01-MAY-2013 200 1000 20
5: 02-MAY-2013 400 1000 40
6: 02-MAY-2013 500 1000 50
7: 02-MAY-2013 50 1000 5
8: 02-MAY-2013 50 1000 5
A more efficient way, if you just want to compute the share, is :
R> dt[,SHARE:=VOLUME/sum(VOLUME)*100,by="TRADE_DATE"]
R> dt
TRADE_DATE TRADER VOLUME SHARE
1: 01-MAY-2013 T1 100 10
2: 01-MAY-2013 T2 200 20
3: 01-MAY-2013 T3 500 50
4: 01-MAY-2013 T4 200 20
5: 02-MAY-2013 T1 400 40
6: 02-MAY-2013 T2 500 50
7: 02-MAY-2013 T3 50 5
8: 02-MAY-2013 T4 50 5
Upvotes: 2