The functions *path
igraph return a list of connections (edges). Some attributes can be extracted from it, but most importantly, you can use the indexes to index the graph or the data.frame with the data.
library(igraph)
ligacoes <- data.frame(
origem = c("A","A", "B", "B", "D"),
destino = c("B","D","C","D", "E"),
valor= c(31.2, 100, 1, 85, 2),
peso = c(1,1,2,1,2))
grafo1 <- graph_from_data_frame(ligacoes)
# Nós que servem apenas de destino:
finais <- as.character(with(ligacoes, destino[!destino %in% origem]))
# Todos os caminhos que saem de A e terminam nos nós finais:
caminhos <- all_simple_paths(grafo1, from = "A", to = finais, mode = "out")
For example, to have the attribute values valor
for the first path connections:
names(caminhos[[1]])
#> [1] "A" "B" "D" "E"
E(grafo1)[caminhos[[1]]]$valor
#> [1] 31.2 100.0 1.0 2.0
Being a list, you can do operations for all paths using the family apply
:
dados <- data.frame(
caminho = sapply(caminhos, function(x) paste(names(x), collapse = "-")),
comprimento = sapply(caminhos, length),
valor_total = sapply(caminhos, function(x) sum(ligacoes[x, "valor"])),
valor_ponderado = sapply(caminhos, function(x) sum(ligacoes[x, "valor"]*ligacoes[x, "peso"]))
)
dados
#> caminho comprimento valor_total valor_ponderado
#> 1 A-B-D-E 4 134.2 137.2
#> 2 A-B-C 3 216.2 216.2
#> 3 A-D-E 3 34.2 37.2
PS: I didn’t understand based on which account you made the value in the example you posted, so I invented a demo account.
You can include an example of the format you want for the final data.frame?
all_simple_paths
and other functions of the type return lists because the paths have different length.– Carlos Eduardo Lagosta
Added specified detail, obg
– user250908