在一组条件下比较 R 中的两个表以查找客户未购买的产品
Comparing two tables in R to find what products customer is not purchasing with a set of conditions
我有两个table如下:
Cust_list <- data.frame(
stringsAsFactors = FALSE,
Customer = c("Mike S.","Tim P.","Steve Z."),
Type = c("Shoes","Socks", "Shoes"),
Product_ID = c(233,6546,296)
)
Product_Table <- data.frame(
stringsAsFactors = FALSE,
Product_ID = c(233,256,296,8536,6546,8946),
Type = c("Shoes","Shoes","Shoes", "Socks","Socks","Socks"),
SubType = c("Basketball", "Basketball", "Baseball", "Ankle", "Knee-High", "Mid")
)
我正在寻找“客户”未在“类型”中购买的“Product_ID”。
例如,Steve Z. 在“鞋子”下购买了产品 ID =“296”和类型 =“鞋子”,但没有购买产品 ID =“233”和“256”。由于 Steve Z. 没有购买 Type = "Socks",因此不会包含在输出中。
另外一个警告,如果客户购买了与子类型 =“篮球”相关的产品 ID,请不要输出与“篮球”相关的产品 ID。由于 Mike S. 已经购买了篮球鞋,因此与篮球鞋相关的其他产品 ID 未包含在输出中。
输出table如下。
在此处输入图片描述
基于 Onyambu 为原始 post 提供的答案,您可以执行以下操作。
library(dplyr)
out <- Cust_list %>%
left_join(Product_Table) %>%
select(Customer, SubType) %>%
filter(SubType == 'Basketball')
select(Cust_list, -Product_ID) %>%
left_join(Product_Table) %>%
anti_join(Cust_list) %>%
anti_join(out)
# Customer Type Product_ID SubType
# 1 Mike S. Shoes 296 Baseball
# 2 Tim P. Socks 8536 Ankle
# 3 Tim P. Socks 8946 Mid
# 4 Steve Z. Shoes 233 Basketball
# 5 Steve Z. Shoes 256 Basketball
我有两个table如下:
Cust_list <- data.frame(
stringsAsFactors = FALSE,
Customer = c("Mike S.","Tim P.","Steve Z."),
Type = c("Shoes","Socks", "Shoes"),
Product_ID = c(233,6546,296)
)
Product_Table <- data.frame(
stringsAsFactors = FALSE,
Product_ID = c(233,256,296,8536,6546,8946),
Type = c("Shoes","Shoes","Shoes", "Socks","Socks","Socks"),
SubType = c("Basketball", "Basketball", "Baseball", "Ankle", "Knee-High", "Mid")
)
我正在寻找“客户”未在“类型”中购买的“Product_ID”。
例如,Steve Z. 在“鞋子”下购买了产品 ID =“296”和类型 =“鞋子”,但没有购买产品 ID =“233”和“256”。由于 Steve Z. 没有购买 Type = "Socks",因此不会包含在输出中。
另外一个警告,如果客户购买了与子类型 =“篮球”相关的产品 ID,请不要输出与“篮球”相关的产品 ID。由于 Mike S. 已经购买了篮球鞋,因此与篮球鞋相关的其他产品 ID 未包含在输出中。
输出table如下。
在此处输入图片描述
基于 Onyambu 为原始 post 提供的答案,您可以执行以下操作。
library(dplyr)
out <- Cust_list %>%
left_join(Product_Table) %>%
select(Customer, SubType) %>%
filter(SubType == 'Basketball')
select(Cust_list, -Product_ID) %>%
left_join(Product_Table) %>%
anti_join(Cust_list) %>%
anti_join(out)
# Customer Type Product_ID SubType
# 1 Mike S. Shoes 296 Baseball
# 2 Tim P. Socks 8536 Ankle
# 3 Tim P. Socks 8946 Mid
# 4 Steve Z. Shoes 233 Basketball
# 5 Steve Z. Shoes 256 Basketball