【发布时间】:2017-12-20 22:35:49
【问题描述】:
我将这个线程提到Create table with all pairs of values from one column in R, counting unique values 和Table of Interactions - Case with pets and houses 了解如何创建 2-way 交互表。 对于所有可能的情况,我怎么能这样做? 另外,我想在这些分类(组合)中找到出现频率和收入。
这是我的输入数据
Customer Product Revenue
1 A Rice 10
2 A Sweet Potato 2
3 A Walnut 4
4 B Rice 3
5 B Walnut 2
6 C Walnut 3
7 C Sweet Potato 4
8 D Rice 3
9 E Sweet Potato 4
10 F Walnut 7
11 G Rice 2
12 G Sweet Potato 3
13 H Sweet Potato 4
14 H Walnut 6
15 I Rice 2
DFI <- structure(list(Customer = c("A", "A", "A", "B", "B", "C", "C",
"D", "E", "F", "G", "G", "H", "H", "I"), Product = c("Rice",
"Sweet Potato", "Walnut", "Rice", "Walnut", "Walnut", "Sweet Potato",
"Rice", "Sweet Potato", "Walnut", "Rice", "Sweet Potato", "Sweet Potato",
"Walnut", "Rice"), Revenue = c(10, 2, 4, 3, 2, 3, 4, 3, 4, 7,
2, 3, 4, 6, 2)), .Names = c("Customer", "Product", "Revenue"), row.names = c(NA,
15L), class = "data.frame")
这是生成产品Sweet PotatoRice和Walnut的所有组合的代码:
Combinations<-do.call(c,lapply(seq_along(unique(DFI$Product)),
combn, x = unique(DFI$Product), simplify = FALSE))
[[1]]
[1] "Rice"
[[2]]
[1] "Sweet Potato"
[[3]]
[1] "Walnut"
[[4]]
[1] "Rice" "Sweet Potato"
[[5]]
[1] "Rice" "Walnut"
[[6]]
[1] "Sweet Potato" "Walnut"
[[7]]
[1] "Rice" "Sweet Potato" "Walnut"
这是我对根据产品类型组合的出现频率的预期输出数据:
Combination Frequency
1 R 2
2 S 1
3 W 1
4 R,S 1
5 S,W 2
6 R,W 1
7 R,S,W 1
DFOUTa <- structure(list(Combination = c("R", "S", "W", "R,S", "S,W", "R,W",
"R,S,W"), Frequency = c(2, 1, 1, 1, 2, 1, 1)), .Names = c("Combination",
"Frequency"), row.names = c(NA, 7L), class = "data.frame")
这是我对分类中收入的预期输出数据(即产品类型的组合):
Combination Revenue
1 R 5
2 S 4
3 W 7
4 R,S 5
5 S,W 17
6 R,W 5
7 R,S,W 16
DFOUTb <- structure(list(Combination = c("R", "S", "W", "R,S", "S,W", "R,W",
"R,S,W"), Revenue = c(5, 4, 7, 5, 17, 5, 16)), .Names = c("Combination",
"Revenue"), row.names = c(NA, 7L), class = "data.frame")
我已经手动生成了上述数据。我已经仔细检查以确保没有错误。
我不确定如何生成我正在寻找的两个输出。我真诚地感谢任何帮助。我更喜欢基于 data.table 的方法,因为我在原始数据集中拥有的数据量很大。
PS:为简洁起见,我在输出文件中分别将产品名称Rice、Sweet Potato 和Walnut 缩短为R、S、W。
【问题讨论】:
-
不确定这是否是一个问题,但到目前为止,这两个答案都将省略 DFI 中未观察到的任何组合/捆绑,因此如果我们删除客户 A,则 RSW 行将丢失,而不是零频率和收入。
标签: r dplyr data.table