【发布时间】:2016-10-21 04:50:46
【问题描述】:
我有一个 3 列的数据框
A B 1
A B 1
A C 1
B A 1
我想对其进行聚合,使其认为 A-B 和 B-A 的组合相同,从而得到 p>
A B 3
A C 1
我该怎么做?
【问题讨论】:
标签: r aggregate combinations
我有一个 3 列的数据框
A B 1
A B 1
A C 1
B A 1
我想对其进行聚合,使其认为 A-B 和 B-A 的组合相同,从而得到 p>
A B 3
A C 1
我该怎么做?
【问题讨论】:
标签: r aggregate combinations
在前两列使用pmin 和pmax,然后按计数分组:
library(dplyr);
df %>% group_by(G1 = pmin(V1, V2), G2 = pmax(V1, V2)) %>% summarise(Count = sum(V3))
Source: local data frame [2 x 3]
Groups: G1 [?]
G1 G2 Count
(chr) (chr) (int)
1 A B 3
2 A C 1
对应的data.table 解决方案是:
library(data.table)
setDT(df)
df[, .(Count = sum(V3)), .(G1 = pmin(V1, V2), G2 = pmax(V1, V2))]
G1 G2 Count
1: A B 3
2: A C 1
数据:
structure(list(V1 = c("A", "A", "A", "B"), V2 = c("B", "B", "C",
"A"), V3 = c(1L, 1L, 1L, 1L)), .Names = c("V1", "V2", "V3"), row.names = c(NA,
-4L), class = "data.frame")
【讨论】: