Search code examples
rigraphadjacency-matrix

How do I convert this adjacency matrix into a graph object?


I have a matrix that represents social interaction data on a CSV, which looks like below:

    `0`   `1`   `2`   `3`   `4`   `5`   `6`   `7`   `8`   `9`
   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
 0     0    29     1     0     1     9     3     0     1     4
 1     1     0     0     1     3     1     0     1     1     1
 2     1     1     0    13     4     0     1     1    15     0
 3     3     0     1     0     1     1     7     1     1     1
 4     1     0     1    98     0     1     1     1     1     2
 5     2     5     1     1     3     0     2     0     1     5
 6     1     1     0     0    12     1     0     2     1     1
 7     1     1     0     1     0     1     9     0     1     2
 8     1     1    17    13   145     1    39     1     0     1
 9    88    23     1     5     1     2     1     7     1     0

I am new to social network analysis, so I am not sure of my terminology, but this seems like a weighted adjacency matrix to me, as we can say from this that student 1 has had 29 interactions with student 0 in the last year. I had this object stored as a data-frame in my RStudio, but when I ran the following code, I received the below error:

> fn <- graph_from_adjacency_matrix(output, weighted = T)
Error in mde(x) : 'list' object cannot be coerced to type 'double'

I've tried converting it to matrix, but that does not seem to work either. Any help concerning this would be really appreciated.


Solution

  • You need to convert your data.frame to matrix first and then apply graph_from_adjacency_matrix, e.g.,

    g <- graph_from_adjacency_matrix(as.matrix(df),weighted = TRUE)
    

    and plot(g) gives

    enter image description here

    Data

    > dput(df)
    structure(list(``0`` = c(0L, 1L, 1L, 3L, 1L, 2L, 1L, 1L, 1L, 
    88L), ``1`` = c(29L, 0L, 1L, 0L, 0L, 5L, 1L, 1L, 1L, 23L), ``2`` = c(1L,
    0L, 0L, 1L, 1L, 1L, 0L, 0L, 17L, 1L), ``3`` = c(0L, 1L, 13L,
    0L, 98L, 1L, 0L, 1L, 13L, 5L), ``4`` = c(1L, 3L, 4L, 1L, 0L,
    3L, 12L, 0L, 145L, 1L), ``5`` = c(9L, 1L, 0L, 1L, 1L, 0L, 1L,
    1L, 1L, 2L), ``6`` = c(3L, 0L, 1L, 7L, 1L, 2L, 0L, 9L, 39L, 1L
    ), ``7`` = c(0L, 1L, 1L, 1L, 1L, 0L, 2L, 0L, 1L, 7L), ``8`` = c(1L,
    1L, 15L, 1L, 1L, 1L, 1L, 1L, 0L, 1L), ``9`` = c(4L, 1L, 0L, 1L,
    2L, 5L, 1L, 2L, 1L, 0L)), class = "data.frame", row.names = c("0",
    "1", "2", "3", "4", "5", "6", "7", "8", "9"))