Turn igraph.vs into dataframe

Asked

Viewed 90 times

0

After obtaining the list of paths originating from a given vertex (e.g. A) through all_simple_paths:

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))

grafo1 <- graph.edgelist(as.matrix(ligacoes[1:2]))
E(grafo1)$valor <- ligacoes$valor

all_simple_paths(grafo1, V(grafo1)["A"])

needed to record the information on a dataframe, someone can help?

For example, for the evaluation of all existing paths originating at vertex A, the ultimate goal would be to obtain something similar to:

inserir a descrição da imagem aqui

  • 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.

  • Added specified detail, obg

1 answer

1


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.

  • With this option I can get the records associated with paths 3,4 and 6. How can I get the other paths cleared (the paths associated with ID 1, 2 and 5)? (paths with origin in A and whose destination is not a vertex obtained in "endings")

  • Check out the help for all_simple_paths: the default is to use all vertices as destination. Just remove to = finais.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.