![](/img/trans.png)
[英]Create a column based on the name of the element list that contain the data frame in R
[英]create list based on data frame in R
我有以下格式的數據框 A
user item
10000000 1 # each user is a 8 digits integer, item is up to 5 digits integer
10000000 2
10000000 3
10000001 1
10000001 4
..............
我想要的是一個列表B,以用戶的名字作為列表元素的名稱,列表元素是一個與該用戶對應的項目向量。
例如
B = list(c(1,2,3),c(1,4),...)
我還需要將名稱粘貼到 B。要應用關聯規則學習,項目需要轉換為字符
最初我使用的是tapply(A$user,A$item, c)
,這使得它與關聯規則包不兼容。 看我的帖子:
但是@sgibb 的解決方案似乎也生成了一個數組,而不是一個列表。
library("arules")
temp <- as(C, "transactions") # C is output using @sgibb's solution
throws error: Error in as(C, "transactions") :
no method or default for coercing “array” to “transactions”
看看tapply
:
df <- read.table(textConnection("
user item
10000000 1
10000000 2
10000000 3
10000001 1
10000001 4"), header=TRUE)
B <- tapply(df$item, df$user, FUN=as.character)
B
# $`10000000`
# [1] "1" "2" "3"
#
# $`10000001`
# [1] "1" "4"
編輯:我不知道arules包,但這里是@alexis_laz 提出的解決方案:
library("arules")
as(split(df$item, df$user), "transactions")
# transactions in sparse format with
# 2 transactions (rows) and
# 4 items (columns)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.