2017-02-15 42 views
1

我有一個data.table看起來是這樣的:由Fruit & Date,然後除以劃分分組資金來獲得率一步到位

Fruit  Date Count 
Apple  8/29/16 20548 
Orange  8/29/16 14744 
Banana  8/29/16 10605 
Strawberry 8/29/16 8341 
Watermelon 8/29/16 7768 
Apple  8/30/16 9819 
Orange  8/30/16 5858 
Banana  8/30/16 3624 
Strawberry 8/30/16 2595 
Watermelon 8/30/16 2291 
Apple  8/31/16 6662 
Orange  8/31/16 6563 
Banana  8/31/16 2073 
Strawberry 8/31/16 1827 
Watermelon 8/31/16 1738 

我怎樣才能得到的Count總和一步完成匯率(如Banana/Apple)?獲取資金是很容易的(注:我也過濾Fruit僅在一次搶二):

d.table[Fruit %in% c('Apple', 'Banana'), .(Sum = sum(Count)), .(Fruit, Date)] 

但我被困在得到我想要的輸出在一個步:

Date Rate 
8/29/16 0.52 
8/30/16 0.37 
8/31/16 0.31 

我應該注意到,我的實際data.table有額外的列(僅用於過濾),我不想重塑我的數據/使用另一個包,如果可能的話,因爲此操作的結果將繪製後根據多個/不斷變化的標準進行過濾,所以我希望能夠輕鬆地重複使用(即一行)。

在此先感謝。

+1

@Frank感謝另一種選擇,我固定的。 – cmaher

回答

4

這應該工作:

d.table[Fruit %in% c('Apple', 'Banana'), 
     .(Rate = sum(Count[Fruit == 'Banana'])/sum(Count[Fruit == 'Apple'])), 
     .(Date)] 
#  Date  Rate 
# 1: 8/29/16 0.5161086 
# 2: 8/30/16 0.3690804 
# 3: 8/31/16 0.3111678 
+0

美麗,謝謝@格雷戈 – cmaher

2

這裏是dcast

library(data.table) 
dcast(setDT(d.table)[Fruit %chin% c("Banana", "Apple")], 
     Date~Fruit, value.var="Count")[, .(Date, Rate = Banana/Apple)] 
#  Date  Rate 
#1: 8/29/16 0.5161086 
#2: 8/30/16 0.3690804 
#3: 8/31/16 0.3111678