3 回答
TA贡献1833条经验 获得超4个赞
一种方法是与创建额外的列pmax和pmin的id1和id2如下。我将data.table在这里使用解决方案。
require(data.table)
DT <- data.table(DF)
# Following mnel's suggestion, g1, g2 could be used directly in by
# and it could be even shortened by using `id1` and id2` as their names
DT.OUT <- DT[, list(size=sum(size)),
by=list(id1 = pmin(id1, id2), id2 = pmax(id1, id2))]
# id1 id2 size
# 1: 5400 5505 18
# 2: 5033 5458 1
# 3: 5452 2873 24
# 4: 5452 5213 2
# 5: 5452 4242 26
# 6: 4823 4823 4
TA贡献1802条经验 获得超5个赞
替代方法:
R> library(igraph)
R> DF
id1 id2 size
1 5400 5505 7
2 5033 5458 1
3 5452 2873 24
4 5452 5213 2
5 5452 4242 26
6 4823 4823 4
7 5505 5400 11
R> g <- graph.data.frame(DF, directed=F)
R> g <- simplify(g, edge.attr.comb="sum", remove.loops=FALSE)
R> DF <- get.data.frame(g)
R> DF
id1 id2 size
1 5400 5505 18
2 5033 5458 1
3 5452 2873 24
4 5452 5213 2
5 5452 4242 26
6 4823 4823 4
TA贡献1864条经验 获得超6个赞
我的aggregate{stats}函数方法:
> df
id1 id2 size
1 5400 5505 7
2 5033 5458 1
3 5452 2873 24
4 5452 5213 2
5 5452 4242 26
6 4823 4823 4
7 5505 5400 11
> df[1:2] <- t(apply(df[1:2], 1, sort))
> aggregate(size ~ id1 + id2, data=df, FUN=sum)
id1 id2 size
1 4823 4823 4
2 2873 5452 24
3 4242 5452 26
4 5213 5452 2
5 5033 5458 1
6 5400 5505 18
- 3 回答
- 0 关注
- 526 浏览
添加回答
举报