问题描述
我试图找出一种方法来获取R中具有唯一用户的产品组合列表.这是[
I trying to figure out a way to get a list of product combinations with unique users in R. This is a follow up question to [Generate matrix of unique user-item cross-product combinations
df <- data.frame(Products=c('Product a', 'Product b', 'Product a',
'Product c', 'Product b', 'Product c', 'Product d'),
Users=c('user1', 'user1', 'user2', 'user1',
'user2','user3', 'user1'))
df的输出是:
Products Users
1 Product a user1
2 Product b user1
3 Product a user2
4 Product c user1
5 Product b user2
6 Product c user3
7 Product d user1
我正在寻找的输出将是所有三种产品组合:
The output I am looking for would be all three product combinations:
Product a/Product b/Product c - 3
Product a/Product b/Product d - 2
Product b/Product c/Product d - 3
...
再次感谢您的帮助.
推荐答案
您似乎希望将逻辑或处理视为用户与每个产品集之间的关系.换句话说,您要计算集合中有多少个唯一用户拥有 any 产品.这是一种实现方法:
It looks like you want logical-OR treatment as the relation between users and each product set. In other words, you want to count how many unique users have any product in the set. Here's one way of doing it:
df <- data.frame(Products=c('Product a','Product b','Product a','Product c','Product b','Product c','Product d'),Users=c('user1','user1','user2','user1','user2','user3','user1'));
comb <- combn(unique(df$Products),3);
data.frame(comb=apply(comb,2,function(x) paste(levels(comb)[x],collapse='/')),num=apply(comb,2,function(x) length(unique(df$Users[as.integer(df$Products)%in%x]))));
## comb num
## 1 Product a/Product b/Product c 3
## 2 Product a/Product b/Product d 2
## 3 Product a/Product c/Product d 3
## 4 Product b/Product c/Product d 3
逻辑与操作比较麻烦,因为我们需要为 every 用户测试 every 产品的存在.我想我使用aggregate()
和match()
找到了一个很好的解决方案:
Logical-AND is trickier, since we need to test for the presence of every product for every user. I think I found a good solution using aggregate()
and match()
:
data.frame(comb=apply(comb,2,function(x) paste(levels(comb)[x],collapse='/')),num=apply(comb,2,function(x) sum(aggregate(Products~Users,df,function(y) !any(is.na(match(x,as.integer(y)))))$Products)));
## comb num
## 1 Product a/Product b/Product c 1
## 2 Product a/Product b/Product d 1
## 3 Product a/Product c/Product d 1
## 4 Product b/Product c/Product d 1
这篇关于R中的产品用法组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!