convert data frame in r to transactions or an itemMatrix?

耗尽温柔 提交于 2020-01-13 11:24:06

问题


I have a data that in data.frame format I want to convert it into transactions or an itemMatrix.

Inspects function in arules support these two data format that's why I'm asking this question


回答1:


library(arules)

example 1: creating transactions from a matrix

a_matrix <- matrix(
      c(1,1,1,0,0,
    1,1,0,0,0,
    1,1,0,1,0,
    0,0,1,0,1,
    1,1,0,1,1), ncol = 5)

set dim names

dimnames(a_matrix) <-  list(
    c("a","b","c","d","e"),
    paste("Tr",c(1:5), sep = ""))

a_matrix

coerce

trans2 <-  as(a_matrix, "transactions")
trans2
inspect(trans2)

example 2: creating transactions from data.frame

a_df <- data.frame(
    age = as.factor(c(6,8,7,6,9,5)), 
    grade = as.factor(c(1,3,1,1,4,1)))  

note: all attributes have to be factors

a_df

coerce

trans3 <- as(a_df, "transactions") 
image(trans3)


来源:https://stackoverflow.com/questions/20758814/convert-data-frame-in-r-to-transactions-or-an-itemmatrix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!