I had a weighted graph represented in a matrix.
aMatrix <- matrix(sample(1:3, 16, replace = TRUE), 4, 4)
row.names(aMatrix) <- LETTERS[1:4]
colnames(aMatrix) <- LETTERS[1:4]
diag(aMatrix) <- 0
knitr::kable(aMatrix, caption = 'An example of a matrix')
| A | B | C | D | |
|---|---|---|---|---|
| A | 0 | 3 | 1 | 2 |
| B | 2 | 0 | 3 | 1 |
| C | 3 | 1 | 0 | 3 |
| D | 2 | 3 | 2 | 0 |
I wanted to import this graph in statnet for analysis. I used as.network function.
library(sna)
library(statnet)
g = as.network(aMatrix, matrix.type = "adjacency", directed = TRUE)
Checking on g. It is not weighted. The weights of edges are ignored.
summary(g)
## Network attributes:
## vertices = 4
## directed = TRUE
## hyper = FALSE
## loops = FALSE
## multiple = FALSE
## bipartite = FALSE
## total edges = 12
## missing edges = 0
## non-missing edges = 12
## density = 1
##
## Vertex attributes:
## vertex.names:
## character valued attribute
## 4 valid vertex names
##
## No edge attributes
##
## Network adjacency matrix:
## A B C D
## A 0 1 1 1
## B 1 0 1 1
## C 1 1 0 1
## D 1 1 1 0
Ignoring weights of the imported graph is the default behavior of network. To import weight, specify ignore.eval = FALSE and names.eval = "weight".
g2 <- as.network(aMatrix,
matrix.type='adjacency',
directed = TRUE,
ignore.eval=FALSE,
names.eval='weight')
summary(g2)
## Network attributes:
## vertices = 4
## directed = TRUE
## hyper = FALSE
## loops = FALSE
## multiple = FALSE
## bipartite = FALSE
## total edges = 12
## missing edges = 0
## non-missing edges = 12
## density = 1
##
## Vertex attributes:
## vertex.names:
## character valued attribute
## 4 valid vertex names
##
## Edge attributes:
##
## weight:
## numeric valued attribute
## attribute summary:
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 1.000 1.750 2.000 2.167 3.000 3.000
##
## Network adjacency matrix:
## A B C D
## A 0 1 1 1
## B 1 0 1 1
## C 1 1 0 1
## D 1 1 1 0
Notice in the above output, under the edge attribute section, there’s the summary about “weight”, that shows the network is weighted. To check the weights:
get.edge.value(g2, "weight")
## [1] 2 3 2 3 1 3 1 3 2 2 1 3
Both arguments (ignore.eval and names.eval) are passed to network from edgeset.constructors. They tell as.network how to handle edge value information. By default, edgevalues are ignored (ignore.eval = TRUE in edgeset.constructors documents).
OK, now we have a weighted network imported ready for analysis! Network metrices differed greatly between weighted and unweighted networks. For more information, start here.