2017-07-25 40 views
0
類別

我有3列的數據幀(DF)兩個字符串:識別號,類別和品牌:R:找到最常見一起每

ID    Category  Brand 
00129   Bits   B89 
00129   Bits   B87 
00129   Bits   B87 
00129   Logs   B32 
00129   Logs   B27 
00129   Logs   B27 
00130   Bits   B12 
00130   Bits   B14 
00130   Bits   B14 
00131   Logs   B32 
00131   Logs   B27 
00131   Logs   B32 
00132   Bits   B77 
00132   Bits   B89 
00132   Bits   B89 

我有200個不同的類別和2000不同品牌。

我想通過ID號找到每最經常一起購買的類別中的兩個品牌:

Category  Brand 
Bits   B89,B87 
Logs   B32,B27 

或:

#$Bits 
    #[1] "B89" "B87" 

#$Logs 
    #[1] "B32" "B27" 

我能想到的唯一辦法是返工的數據幀看起來像這樣以確保它是通過確認不同的ID號來計算的:

 B89 B87 B32 B27 B12 B14 
1 1  2  1  2  0  0 
2 0  0  0  0  1  2 
3 0  0  2  1  0  0 
4 2  1  0  0  0  0 

然後返回已填充了值大於0的列當某一列都將填充大於0

list1 =(setNames(object = lapply(1:NCOL(df), function(i) 
    unique(colnames(df)[-i][which(as.matrix(df[which(df[,i] > 0),i])>0, 
            arr.ind = TRUE)[,2]])), 
    nm = colnames(df))) 

值但後來我犧牲的範疇,我需要的。有關如何解決這個問題的任何想法?

回答

0

這可能會訣竅。結束了data.table和dplyr的組合,因爲我對data.table還不是很熟悉。

dt = data.table(read.table(text="ID    category    brand 
00129   Bits   B89 
00129   Bits   B87 
00129   Bits   B87 
00129   Logs   B32 
00129   Logs   B27 
00129   Logs   B27 
00130   Bits   B12 
00130   Bits   B14 
00130   Bits   B14 
00131   Logs   B32 
00131   Logs   B27 
00131   Logs   B32 
00132   Bits   B77 
00132   Bits   B89 
00132   Bits   B89",header=T)) 

library(data.table) 
library(dplyr) 

# get all combinations of two purchases. 
dt = dt[,.(list(unique(brand))),.(ID,category)][, .(combn(unlist(V1), 2,simplify=FALSE)),.(ID,category)] 

# concatenate those two purchases to a string 
dt$V1 = unlist(lapply(dt$V1,function(x) {paste(x,collapse=", ")})) 

# fetch only the top per category 
dt %>% group_by(V1,category) %>% summarize(n=n()) %>% group_by(category) %>% top_n(n = 1) %>% select(-n) 

輸出:

 V1 category 
1 B12, B14  Bits 
2 B32, B27  Logs 
3 B77, B89  Bits 
4 B89, B87  Bits 

我認爲這是正確的,考慮你的數據集,雖然它沒有你預期的輸出匹配嗎?

可以選擇添加

dt %>% group_by(ID,category) %>% mutate(unique_types = n_distinct(brand)) %>% filter(unique_types>1) 

在前面,如果有,也只是一個單一的品牌購買,因爲combn(n,m)將無法​​正常工作,如果length(n)<m