Search code examples
rlistmatrixapplysparse-matrix

Turning a sparse adjacency list into a full matrix in R


I have seen similar questions to this in my research on this site, but not this exact question (most answers involve creating a sparse matrix from a list).

I have a list of adjacent polygons, but wish to convert it to a full matrix. I can do this rather clunkily with nested for loops, but I am trying to improve my coding by relying less on these. So in essence, what I would like is to get from this:

my_list <- list("1" = c(2, 3),
                "2" = 1,
                "3" = 1)

to something that looks like this:

#     [,1] [,2] [,3]
#[1,]    0    1    1
#[2,]    1    0    0
#[3,]    1    0    0

without resorting to this:

for(i in 1:3{
 for(j in 1:3{
  [look to list to see if there is a value corresponding to (i, j),
   if so insert 1, if not, zero]
 }
}

Thank you very much for your time.


Solution

  • You can use sapply :

    n <- 1:max(unlist(my_list))
    sapply(my_list, function(x) +(n %in% x))
    
    #     [,1] [,2] [,3]
    #[1,]    0    1    1
    #[2,]    1    0    0
    #[3,]    1    0    0