对于图中的每条边,我想添加一个数字属性(权重),它是事件顶点属性(概率)的乘积。我可以通过在边缘上循环来做到这一点;那是:
for (i in E(G)) {
ind <- V(G)[inc(i)]
p <- get.vertex.attribute(G, name = "prob", index=ind)
E(G)[i]$weight <- prod(p)
}
然而,这对于我的图表来说相当慢(|V| ~= 20,000 和 |E| ~= 200,000)。有没有更快的方法来完成这个操作?
这可能是最快的解决方案。关键是矢量化。
library(igraph)
G <- graph.full(45)
set.seed(1)
V(G)$prob <- pnorm(vcount(G))
## Original solution
system.time(
for (i in E(G)) {
ind <- V(G)[inc(i)]
p <- get.vertex.attribute(G, name = "prob", index=ind)
E(G)[i]$wt.1 <- prod(p)
}
)
#> user system elapsed
#> 1.776 0.011 1.787
## sapply solution
system.time(
E(G)$wt.2 <- sapply(E(G), function(e) prod(V(G)[inc(e)]$prob))
)
#> user system elapsed
#> 1.275 0.003 1.279
## vectorized solution
system.time({
el <- get.edgelist(G)
E(G)$wt.3 <- V(G)[el[, 1]]$prob * V(G)[el[, 2]]$prob
})
#> user system elapsed
#> 0.003 0.000 0.003
## are they the same?
identical(E(G)$wt.1, E(G)$wt.2)
#> [1] TRUE
identical(E(G)$wt.1, E(G)$wt.3)
#> [1] TRUE
矢量化解决方案似乎快了大约 500 倍,尽管需要更多更好的测量来更精确地评估这一点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)