Group vertices as a function of Weights

Asked

Viewed 34 times

0

Based on a link df I want to select all possible paths consisting only of vertices whose links check a certain condition in this case value >=3

library(igraph)
library(dplyr)

df <- data.frame(
    origem = c("A", "A", "A", "B", "C", "F", "D", "C"),
    destino = c("B", "C", "D", "E", "F", "G", "H", "G"),
    valor = c(3, 4, 2, 1, 5, 2, 7, 6))

df <- df %>% filter ( valor >= 3)

The goal is to group all vertices that are included in paths with value >=3 recording in a date.frame the ID of the group and for each ID the identification of the vertices that constitute it (a vertex will not be present in more than one group).

In the presented case it would have 2 groups constituted as follows:

 ID    X
  1    A
  1    B
  1    C
  1    F
  1    G
  2    D
  2    H

1 answer

2


Using igraph, can generate a graph from a subset and use clusters to check the groups formed:

grafo <- graph_from_data_frame(subset(df, valor >= 3), directed = FALSE)

# Ou, se já está com os dados completos como igraph:
grafo.f <- graph_from_data_frame(df, directed = FALSE)
grafo <- subgraph.edges(grafo.f, E(grafo.f)[valor >= 3])

clusters(grafo)$membership
#> A C D B F H G
#> 1 1 2 1 1 2 1

plot(cluster_label_prop(grafo), grafo, edge.label = E(grafo)$valor)

inserir a descrição da imagem aqui

If you need the result as data frame.:

grupos <- clusters(grafo)$membership

resultado <- data.frame(ID = names(grupos), X = grupos)
# ou, se estiver usando tidyverse:
resultado <- tibble::enframe(grupos)
  • Obg by the help. How to place the 2 obtained columns in a df: vertices and group to which they belong?

  • I’ll edit the answer to include.

Browser other questions tagged

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