How to convert object of Transaction to Dataframe in R

99封情书 提交于 2020-02-28 18:45:26

问题


How to convert the Dataset(Groceries) in arules package to dataframe.

class(Groceries)
[1] "transactions"
attr(,"package")
[1] "arules"

回答1:


You need to specify what is actually needed. I don't see an as.data.frame.transactions function in the help page for the arules-package. The data-item Groceries does have a dataframe embedded in it but whether that is what you want seems unlikely:

str(Groceries)
Formal class 'transactions' [package "arules"] with 3 slots
  ..@ data       :Formal class 'ngCMatrix' [package "Matrix"] with 5 slots
  .. .. ..@ i       : int [1:43367] 13 60 69 78 14 29 98 24 15 29 ...
  .. .. ..@ p       : int [1:9836] 0 4 7 8 12 16 21 22 27 28 ...
  .. .. ..@ Dim     : int [1:2] 169 9835
  .. .. ..@ Dimnames:List of 2
  .. .. .. ..$ : NULL
  .. .. .. ..$ : NULL
  .. .. ..@ factors : list()
  ..@ itemInfo   :'data.frame': 169 obs. of  3 variables:
  .. ..$ labels: chr [1:169] "frankfurter" "sausage" "liver loaf" "ham" ...
  .. ..$ level2: Factor w/ 55 levels "baby food","bags",..: 44 44 44 44 44 44 44 42 42 41 ...
  .. ..$ level1: Factor w/ 10 levels "canned food",..: 6 6 6 6 6 6 6 6 6 6 ...
  ..@ itemsetInfo:'data.frame': 0 obs. of  0 variables

I'm guessing you actually want:

as.matrix( Groceries@data )

Possibly adding the Groceries@ itemInfo$ labels as rownames




回答2:


arules uses S4 type objects, but the transaction data is stored in a transposed sparse matrix. You should not directly access the data using @. Use coercion to access the transaction data. This will make sure that the data is in a proper format with correct item labels.

Examples:

as(Groceries, "matrix")
as(Groceries, "list")

matrix is a logical transaction-by-items matrix and list produces a list of transaction sets. For details, have a look at the coercion methods in ?transactions.



来源:https://stackoverflow.com/questions/41972270/how-to-convert-object-of-transaction-to-dataframe-in-r

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