Converting to Transactions in R for arules library

Hi All,

It has been a long time; Today I will provide a simple snippet which helped me in Association rules mining in R. Typically when you are extracting transaction data from a Database, it will not be in a transaction level. It is in an item level.

Capture

But the way any self respecting data modeller will store them in RDBMS is

Capture

And the arules library in R requires the datastructure in a “Transactions” class, which is a fancy name for a matrix. So, below is the snippet to convert tabular list to matrix and then to transactions class;


# converts a list/frame to matrix

train.mat <- acast(train, account~product, value.var = "count")

# zero all NAs

which(is.na(train.mat))
for(i in 1:nrow(train.mat))
{
for(j in 1:ncol(train.mat)){
if(is.na(train.mat[i,j]))
{
train.mat[i,j]=0
}
}
}

# converts matrix to transactions

train.trans <- as(train.mat, "transactions")

Hope this helps!!!