2015-06-02 22 views
3

我正在嘗試向現有數據框添加一列,以便該列定義了每個用戶已購買的不同產品的數量。玩具的例子是創建一個R中出現次數的列

Customer Product 
1   Chocolate 
1   Candy 
1   Soda 
2   Chocolate 
2   Chocolate 
2   Chocolate 
3   Insulin 
3   Candy 

對輸出應該是

Customer Product  #Products 
1   Chocolate 3 
1   Candy  3 
1   Soda  3 
2   Chocolate 1 
2   Chocolate 1 
2   Chocolate 1 
3   Insulin  2 
3   Candy  2 

我想for循環做到這一點沒有,因爲我有幾百萬行,並會採取永遠。我已經使用data.table和其他方法來獲取每個客戶的產品數量,但我不知道如何輕鬆地將其作爲列添加到現有數據框中。

在此先感謝!

+1

先從[HTML護身符(https://github.com/Rdatatable/data.table/wiki/Getting-started)開始使用data.table .. – Arun

+0

謝謝@Arun - 我一直在尋找那樣的東西! –

回答

2

在基地RI建議ave

within(mydf, { 
    count = ave(Product, Customer, FUN = function(x) length(unique(x))) 
}) 
## Customer Product count 
## 1  1 Chocolate  3 
## 2  1  Candy  3 
## 3  1  Soda  3 
## 4  2 Chocolate  1 
## 5  2 Chocolate  1 
## 6  2 Chocolate  1 
## 7  3 Insulin  2 
## 8  3  Candy  2 

你也可以嘗試 「data.table」 包:

library(data.table) 
as.data.table(mydf)[, count := length(unique(Product)), by = Customer][] 
## Customer Product count 
## 1:  1 Chocolate  3 
## 2:  1  Candy  3 
## 3:  1  Soda  3 
## 4:  2 Chocolate  1 
## 5:  2 Chocolate  1 
## 6:  2 Chocolate  1 
## 7:  3 Insulin  2 
## 8:  3  Candy  2 
+0

美麗的阿難!我一直在努力使它與data.table(這對我來說是全新的)一起工作,因爲它太快了,但我無法理解語法來獲取所有變量列以及結果。你能解釋一下你用過的語法嗎? –

+0

@tkoz_dk,我只是稍微編輯了代碼。現在它更有意義嗎? ':='是通過引用分配的,最後的'[]'是打印輸出。 – A5C1D2H2I1M1N2O1R2T1

+0

是的,現在我明白了。非常感謝您的幫助! –

1

你要善於用類似的東西(假設df是您的數據):

df.agr=aggregate(Product~Customer,data=df, FUN=function(x) length(unique(x))) 
df=cbind(df, Count=apply(df, MARGIN=1, FUN=function(r) df.agr$Product[match(r[1],df.agr$Customer)])) 

它不會被速度極快,但絕對不是更快。

+0

感謝您的回答。幾乎在那裏,我認爲 - 在最初的問題中,我沒有明確說明這一點:代碼給了我一個客戶購買的物品數量的計數,並且我想要計算他/她不同物品的數量已經購買 - 查看輸出示例進行說明。 –

+0

編輯我的答案。 – cyberj0g

+0

它就像一個魅力!謝謝! –

1

我用plyr對於任何涉及拆分申請-結合。在這種情況下,我們通過Customer分割數據和應用上Product長度,獨特的功能,然後結合的情況下,結果

require(plyr) 
ddply(df, .(Customer), transform, num.products = length(unique(Product))) 

    Customer Product num.products 
1  1 Chocolate   3 
2  1  Candy   3 
3  1  Soda   3 
4  2 Chocolate   1 
5  2 Chocolate   1 
6  2 Chocolate   1 
7  3 Insulin   2 
8  3  Candy   2 

獎金你想有一個小的總結數據框出於此。

ddply(df, .(Customer), summarize, num.products = length(unique(Product))) 

    Customer num.products 
1  1   3 
2  2   1 
3  3   2 
相關問題