GIORIGO
GIORIGO

Reputation: 59

R - Create a network from a matrix

I have a dataset similar to this:

Abruzzo<- c(1,0.76,0.8,0.90)
Campania<- c(0.76,1,0.62,0.69)
Calabria <- c(0.80,0.62,1,0.85)
Puglia <- c(0.90,0.69,0.85,1)
X <-data.frame(Abruzzo,Campania,Calabria,Puglia)
row.names(X)<- c ('Abruzzo','Campania', 'Calabria', 'Puglia')

This matrix contains cosine similarity values. I would like to create a network (with igraph) where the 4 nodes (Abruzzo, Campania, Calabria, Puglia) are all interconnected, and the size of the link depends on the corresponding value of the matrix. Thanks

Upvotes: 1

Views: 1613

Answers (1)

Ian Campbell
Ian Campbell

Reputation: 24790

You have a weighted adjacency matrix. Use igraph::graph_from_adjacency_matrix:

library(igraph)
X <- as.matrix(X)
diag(X) <- 0
g <- graph_from_adjacency_matrix(X, mode = "lower", weighted = "weight")
plot(g, edge.width = E(g)$weight, edge.label = E(g)$weight)

enter image description here

If you want a directed graph, change mode to "directed".

Upvotes: 4

Related Questions