[R-sig-Geo] Class nb (spdep) from class igraph

Paul Galpern pgalpern at gmail.com
Tue Jan 22 16:13:09 CET 2013


Thanks Roger.

Apologies: the two functions I intended to reference in my original post 
were igraph::get.adjacency() and igraph::get.edgelist() which produce a 
slightly clearer broth (I like this expression "fish soup").

Your suggestion requiring a third party package seems the easiest. I 
found another 3rd party approach using the ade4 package which has two 
functions ade4::neig() and ade4::neig2nb() that together do the trick.  
(Note this approach ignores edge weights).

library(igraph)
library(spdep)

## igraph2nb
## Convert igraph undirected graphs (of S3 class igraph) into nb objects 
(class spdep)
## No checking performed
igraph2nb <- function(gr) {
     library(ade4)
     return(neig2nb(neig(edges=get.edgelist(gr))))
}

## Create simple igraph object
ringGraph <- graph.ring(10)

## Convert to nb object
ringGraph_nb <- igraph2nb(ringGraph)

## Visualize using plot.nb
plot(ringGraph_nb, coords=cbind(runif(10), runif(10)))


Best,
Paul

On 22/01/2013 1:44 AM, Roger Bivand wrote:
> On Mon, 21 Jan 2013, Paul Galpern wrote:
>
>> Is there a simple way to produce an nb object (in spdep) from a 
>> weighted or unweighted undirected graph (in igraph).
>
> No, unless you can make them back into a (possibly sparse) adjacency 
> matrix. The igraph S3 class (returned by graph.adjacency) is fish 
> soup, while the input adjacency matrix would work directly with 
> spdep::mat2listw().
>
> Please provide sample code to illustrate your question - preferably 
> showing how to go from and to nb objects. If you add igraph <-> 
> graphNEL <-> sparse matrix, you can get there, but not igraph <-> nb 
> in one hop, going through graphNEL is needed:
>
> library(igraph)
> set.seed(1)
> adjm <- matrix(sample(0:1, 100, replace=TRUE, prob=c(0.8,0.2)), nc=10)
> g1 <- graph.adjacency(adjm)
> library(graph)
> g1G <- igraph.to.graphNEL(g1)
> library(Matrix)
> sM <- as(g1G, "sparseMatrix")
> library(spdep)
> nb <- mat2listw(sM)$neighbours
> nb
> sum(adjm)
>
> If you wanted to contribute a function, the igraph.[to|from].graphNEL 
> code would probably show how it could be done, because graphNEL are 
> quite similar to listw objects.
>
> Hope this helps,
>
> Roger
>
>>
>> Could the output of igraph::graph.adjacency(x) be converted to class nb?
>>
>> Alternatively, igraph::graph.edgelist(x) could be manipulated into 
>> class Graph, and then spdep::graph2nb() used.
>>
>> Am I missing an obvious way to do this?
>>
>> Thanks,
>> Paul
>>
>>
>

-- 
Paul Galpern
Natural Resources Institute
70 Dysart Road
University of Manitoba
Winnipeg, Manitoba, Canada R3T 2M6
http://borealscape.ca



More information about the R-sig-Geo mailing list