嗨,所以我正在尝试验证我的购物篮关联规则,并且我希望将我的数据框组合创建到同一列中。
例如,来自UserId和Basket的DF,
> head(validDF)
UserID Basket
1 935 Toy Story (1995)
2 935 Dead Man Walking (1995)
3 935 Mr. Holland's Opus (1995)
4 936 Fargo (1996)
5 936 Rock The (1996)
6 936 Twister (1996)
我想创建这些组合:
UserID Basket
1 935 Toy Story (1995), Dead Man Walking (1995)
2 935 Dead Man Walking (1995), Toy Story (1995)
3 935 Mr. Holland's Opus (1995), Toy Story (1995)
4 935 Mr. Holland's Opus (1995), Dead Man Walking (1995)
5 936 Fargo (1996), Rock The (1996)
6 936 Rock The (1996), Fargo (1996)
7 936 Twister (1996), Fargo (1996)
8 936 Twister (1996), Rock The (1996)
任何人都知道怎么做?
使用R根据数据集中的UserId生成这些组合,R不是我最强的语言。所以任何帮助都表示赞赏!
答案 0 :(得分:0)
# data frame
validDF = data.frame(
UserID = c(935, 935, 935, 936, 936, 936),
Basket = c("Toy Story (1995)", "Dead Man Walking (1995)", "Mr. Holland's Opus (1995)",
"Fargo (1996)", "Rock The (1996)", "Twister (1996)"))
res = lapply(unique(validDF$UserID), function(x){
ls_Basket <- as.character(validDF$Basket[validDF$UserID == x])
res_int = permutations(n = 3, r=2, v= ls_Basket)
data.frame(UserID = x, Basket = apply(res_int, 1, paste, collapse = ", "))
})
res <- do.call(rbind, res)
但在你的例子中,你混合了排列(3部电影=&gt; 6种排列)和组合(3部电影=&gt; 3种组合)