r - 按产品编号对 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 的推荐产品数量。
任何帮助表示赞赏。
解决方案
如果要按 计算推荐产品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"
推荐阅读
- c++ - 根据一些给定的限制计算有效密码的数量
- python-3.x - 如何以百分比抑制 7zip 详细输出但提取状态?
- php - 如何使用 payflow pro api php 获取退款交易详情
- networking - NIC 内存管理和 RSS 队列
- php - 如何在完整项目中将默认数据表页长设置为 100?
- email - 收到新邮件时从 webmail 请求回调 URL
- gradle - Gradle 中的归档分类器是什么?
- google-apps-script - 用于创建文件目录的 Google 脚本
- macos - 如何在 xamarin 表单中将 webview 背景黑色更改为白色
- node.js - Twilio 消息未在 cron lamba 上触发