sah*_*ang 2 attributes r igraph
对于图中的每个边,我想添加一个数值属性(权重),它是事件顶点的属性(概率)的乘积.我可以通过循环边缘来做到这一点; 那是:
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)
}
Run Code Online (Sandbox Code Playgroud)
但是,这对于我的图表来说速度很慢(| 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
Run Code Online (Sandbox Code Playgroud)
矢量化解决方案似乎快了大约500倍,尽管需要更多更好的测量来更精确地评估它.