首页 > 解决方案 > 按产品编号对 R 中的数据进行分组

问题描述

我从一个网站下载了亚马逊数据,其中显示了客户在购买某种产品后购买的产品编号和推荐产品。

例如数据文件如下所示:

ProductID   Recommended Product ID
0           1
0           2
0           3
0           4
1           0
1           2

structure(list(ProductID = structure(c(1L, 1L, 1L, 1L, 2L, 2L
), .Label = c("0", "1"), class = "factor"), Recommended_Product_ID = structure(c(1L, 
2L, 3L, 4L, 2L, 3L), .Label = c("1", "2", "3", "4"), class = "factor")), .Names = c("ProductID", 
"Recommended_Product_ID"), row.names = c(NA, -6L), class = "data.frame")

这是数据文件的示例。现在我们必须使用 Bipartite 包来执行此操作,所以我必须跳过一些在数据集中重复的元素,就像在上面的数据集中我们有一个连接:

0   1

所以,既然我们有从 0 到 1 的连接,那么我们跳过:

1   0

这是我目前拥有的:

library(bipartite)
library(igraph)
library(lpbrim)
data <- read.csv("./dataset.txt", header = F, sep = "\t", col.names = c("product1", "recommproduct"))
aggLevel = length(list(data$product1))

在代码中,我试图找出是否有人购买了 ID 为 0 的产品,然后使用该 ID 购买了多少其他产品。因此,在数据集中,它显示了推荐产品 ID 列表中使用相应产品 ID 购买的其他产品 ID。

当我打印变量aggLevel时,我得到 1,而不是得到对应产品 ID 的推荐产品数量。

任何帮助表示赞赏。

标签: r

解决方案


如果要按 计算推荐产品ProductID,这里有 3 种基本 R 方式。

xtabs( ~ ProductID, data)
tapply(data$Recommended, data$ProductID, length)
aggregate(Recommended ~ ProductID, data, length)

和一个包dplyr

library(dplyr)
data %>% group_by(ProductID) %>% summarise(Count = n())

数据。

data <- read.csv(text = "
ProductID   ,Recommended Product ID
0           ,1
0           ,2
0           ,3
0           ,4
1           ,2
1           ,3                   
")
names(data)[2] <- "Recommended"

推荐阅读