2016-10-10 52 views
1

我有邊緣形式的事務數據,並且需要創建基於事務的稀疏矩陣,該矩陣可以與arules R包一起使用。目前我正在使用tidyr軟件包中的「spread」將邊緣列表轉換爲矩陣,並將每行轉換爲「basket ID」,然後將其轉換爲邏輯,因爲我無法將數量信息與arules一起使用,所以將其轉換爲「交易「爲基礎的數據類型,請參閱下面的R代碼示例:將邊緣列表轉換爲arules事務稀疏鄰接矩陣

我的問題是,這適用於小集籃子/交易,但是當我有更多時,由於」傳播「功能導致內存問題。我想知道是否有與原邊視圖到arules用途?在此先感謝您的任何建議交易數據類型轉換了更大的內存/資源有效方式!

## Load libraries 

library(tidyr) 
library(arules) 

## Create an example of the transactions that I am analizing 

TransEdgeList = data.frame(BasketID=c(1,1,2,2,3,3,3), 
           Item=c(10,11,10,12,10,11,13), 
           Qty=c(1,1,2,3,1,2,1)) 

#convert to something that arules can transform 
BasketDataFrame = spread(TransEdgeList, Item, Qty) 

#convert to logical 
BasketDataFrame[, 2:dim(BasketDataFrame)[2]]= 
    !is.na(BasketDataFrame[, 2:dim(BasketDataFrame)[2]]) 

#convert to a transaction sparse matrix that arules can use 
BasketMatrix = as(BasketDataFrame[, 2:dim(BasketDataFrame)[2]], "transactions") 

BasketMatrix 
+0

是'table'還好嗎? '表(TransEdgeList [1:2])'或'xtabs(〜BasketID + Item,data = TransEdgeList,sparse = TRUE)' – user20650

回答

2

我會手工創建一個稀布L ogical triplet矩陣(ngTMatrix),將其轉換爲稀疏的ngCMatrix,然後可以將其轉換爲交易對象。這種方式從來沒有創建完整的矩陣表示,你應該記憶明智。

library(arules) 
library(Matrix) 

TransEdgeList <- data.frame(BasketID=c(1,1,2,2,3,3,3), 
    Item=c(10,11,10,12,10,11,13), 
    Qty=c(1,1,2,3,1,2,1)) 

m <- new("ngTMatrix", 
    i = as.integer(TransEdgeList$Item)-1L, 
    j = as.integer(TransEdgeList$BasketID)-1L, 
    Dim = as.integer(c(max(TransEdgeList$Item), max(TransEdgeList$BasketID)))) 

m <- as(m, "ngCMatrix") 

tr <- as(m, "transactions") 
inspect(tr) 

    items  itemsetID 
[1] {10,11} 1   
[2] {10,12} 2   
[3] {10,11,13} 3 
+0

謝謝邁克爾!這只是我需要的。 – Kevin

+0

另一種方法是使用'?'的例子。交易「:a_df3 < - data.frame( TID = c(1,1,2,2,2,3), item = c(」a「,」b「,」a「,」b「, 「c」,「b」) ); trans4 < - as(split(a_df3 [,「item」],a_df3 [,「TID」]),「transactions」)'。我認爲應該有類似的表現。 –