2017-10-04 66 views
0

我有一個包含約100萬個交易行的數據集,我試圖從一個data.frame轉換爲一個交易類,以用於arules包中的apriori函數。我正在使用文檔中討論的格式:R arules - 快速創建交易的方式

a_df3 <- data.frame(
TID = c(1,1,2,2,2,3), 
item=c("a","b","a","b","c", "b") 
) 
a_df3 
trans4 <- as(split(a_df3[,"item"], a_df3[,"TID"]), "transactions") 

但是,對於大塊數據,這是非常緩慢的。有什麼方法可以加快速度?

回答

0

從包Matrix轉換一個列表(split的結果)稀疏ngCMatrix是昂貴的。主要是因爲我們無法確定提供的交易中是否有重複項目以及交易中的項目是否已排序......

以下是一些可將您的第一個data.frame直接轉換爲交易的實驗代碼

library("arules") 
library("Matrix") 

a_df <- data.frame(
    TID = c(1,1,2,2,2,3), 
    item=c("a","b","a","b","c", "b") 
) 

j <- as.integer(a_df$TID) 
item <- factor(a_df$item) 
i <- as.integer(item) 

ngT <- new("ngTMatrix", i = i-1L, j = j-1L, Dim = c(max(i), max(j)), 
    Dimnames = list(levels(item), NULL)) 
ngC <- as(ngT, "ngCMatrix") 
trans <- as(ngC, "transactions") 

inspect(trans) 

    items itemsetID 
[1] {a,b} 1   
[2] {a,b,c} 2   
[3] {b}  3 

這需要幾百秒而不是一分鐘的交易。小心使用代碼(它不檢查輸入數據),直到進入arules包。