gpt4 book ai didi

r - 如何使用 igraph 提取 R 中所有最短路径的边类型?

转载 作者:行者123 更新时间:2023-12-04 12:31:13 26 4
gpt4 key购买 nike

igraph 有两个有用的函数,shortest_pathsall_shortest_paths。前者输出最短路径之一,另一个输出所有路径。不过前者还可以输出路径的边类型,而后者好像不行。

如何使用 all_shortest_paths 提取所有最短路径的“边类型”?我在下面提供了澄清代码:

library(igraph)
m <- read.table(row.names=1, header=TRUE, text=
" A B C D
A 0 1 1 0
B 0 0 0 1
C 0 0 0 1
D 0 0 0 0")
m <- as.matrix(m)
ig <- graph.adjacency(m, mode="directed")
plot(ig)
E(ig)
for (i in 1:length(E(ig))) {

if (i == 4) {

E(ig)[i]$type <- -1
} else {

E(ig)[i]$type <- 1
}

}

###This gets one of the shortest paths
test1 <- shortest_paths(ig, from = V(ig)[1], to = V(ig)[4], mode = "out", output = "epath")

###This outputs the types for the shortest path above
test1$epath[[1]]$type

###This gets all the shortest paths
test2 <- all_shortest_paths(ig, from = V(ig)[1], to = V(ig)[4], mode = "out")

###The code below doesn't work. How do I get the types for ALL the shortest paths?
test2$res[[1]]$type

最佳答案

试试下面的代码

df <- get.data.frame(ig)
lapply(
test2$res,
function(x) {
nm <- names(x)
merge(
df,
data.frame(from = head(nm, -1), to = tail(nm, -1))
)$type
}
)

你会得到

[[1]]
[1] 1 -1

[[2]]
[1] 1 1

如果想查看更多信息,可以使用

df <- get.data.frame(ig)
lapply(
test2$res,
function(x) {
nm <- names(x)
merge(
df,
data.frame(from = head(nm, -1), to = tail(nm, -1))
)
}
)

你会得到

[[1]]
from to type
1 A C 1
2 C D -1

[[2]]
from to type
1 A B 1
2 B D 1

关于r - 如何使用 igraph 提取 R 中所有最短路径的边类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68930051/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com