我想在我的数据中分离独特的项目组的组合 - 与键列关联的行的唯一分组,而不是唯一项目,这是最常用的唯一功能对于。这个问题需要仔细阅读...所以,请先善待消化这个例子。在多元数据中找到唯一的“项目组”
要清楚,我不想要组列的唯一子集,也不需要唯一项目子集,甚至不需要组和项目的唯一组合。我知道这些已被其他地方覆盖unique() for more than one variable。我想要的是独特的项目集,其中集合由组定义。
下面是一个例子
set.seed(1234)
library(data.table)
A <- data.table(group = rep(c("A","B","C","D","E","F"),each = 4),
item = c(1, 2, 4, 3, 5, 2, 3, 6, 10, 12, 1, 2, 1, 2, 4, 3, 6, 3,
5, 2, 10, 12, 1, 2), c = runif(8))
A <- A[-23, ] #so we can have an example of unbalanced groups
> A
group item c
1: A 1 0.15904600
2: A 2 0.03999592
3: A 4 0.21879954
4: A 3 0.81059855
5: B 5 0.52569755
6: B 2 0.91465817
7: B 3 0.83134505
8: B 6 0.04577026
9: C 10 0.15904600
10: C 12 0.03999592
11: C 1 0.21879954
12: C 2 0.81059855
13: D 1 0.52569755
14: D 2 0.91465817
15: D 4 0.83134505
16: D 3 0.04577026
17: E 6 0.15904600
18: E 3 0.03999592
19: E 5 0.21879954
20: E 2 0.81059855
21: F 10 0.52569755
22: F 12 0.91465817
23: F 2 0.04577026
#The unique groups are A:F, and the unique items are 1:6,10,12.
#The unique sets of items are: # (set1) 1,2,3,4; (set2) 5,2,3,6;
#(set3) 10,2,1,2; (set4) 10,12,2
我想找回物品的这些独特的套(再次指出,该项目组由形成)。 (第三列目前意思不大,为了好玩,我在每个'item'中加入了和数)。 输出表应该是这样的:
group item c
A 1 0.68474355 #note that groups A and D share this same set of items (set1)
A 2 0.95465409
A 4 1.05014459# c sums groupAitem4$c with groupDitem4$c
A 3 0.85636881
B 5 0.74449709 # group E has the same items (set2), even if not the same order, c is totaled by item.
B 2 1.72525672
B 3 0.87134097
B 6 0.20481626
C 10 0.159046
C 12 0.03999592
C 1 0.21879954
C 2 0.81059855
F 10 0.52569755 #Not the same as group C
F 12 0.91465817
F 2 0.04577026
我想有可能是通过重塑去的方式,将是很尴尬的。我的数据很大,所以像data.table
这样高效的程序将非常值得赞赏。
不花哨/有效,但'strsplit(独特(paste0(A $组“”,A $项目)),“,”)' –
你想如何处理属于每个唯一配对的各种'A $ c'值?看看'aggregate'和'plyr'的一般想法。 –
[Unique()for multiple variable)可能的重复(http://stackoverflow.com/questions/7790732/unique-for-more-than-one-variable)和http://stackoverflow.com/questions/ 9944816/unique-on-a-dataframe-with-only-selected-columns?rq = 1 and http://stackoverflow.com/questions/10873203/r-find-all-unique-values-among-subsets-of- a-data-frame?rq = 1 –