Skip to content

exporting neighbor list to a text file...

2 messages · Alok K Bohara, PhD, Roger Bivand

#
(I am new to this group.)   I have a two-part question.  I have a shape 
file for the US states (excluding Alaska and Hawaii)

I am trying to export (or save)  the nearest neighbor list to a csv or 
text file.

This is what I did

***
USs <- readShapeSpatial("usa")

# Creating Neighbor List
USs.nb <- poly2nb(USs)
IDs <- row.names(as(USs, "data.frame"))

NeighMap <- nb2gra(USs.nb)
NeighList <- get.neighbor(NeighMap, IDs)
summary(NeighList)

(IDs extracted above begins from 0, 1, 2,... 50).

***

Is there any way I could save/export the neigbor list as follows where 
the first line is the  number of cells/states (49) and the rest of the 
lines as whown below:

49
1  3 4 18 21
2  2 5 4
3  2 8 12 15 32
.
.
49  3 9 11
  etc...

****

Thanks.


Sincerely,

Alok Bohara
UNM
#
On Thu, 16 Aug 2012, Alok K Bohara, PhD wrote:

            
Do you have a reason for using this format rather than the standard GAL 
format, which is:

n
1 #neigh1
neigh11 neigh12 ...
2 #neigh2
neigh21 neigh22 ...

etc, that is two lines per observation, the first giving its ID and the 
count of neighbours, and which can be read by many applications?

The following will do what you want, but I don't think you should:

library(spdep)
data(columbus)
tf <- tempfile()
con <- file(tf, open="wt")
n <- length(col.gal.nb)
writeLines(paste(n), con=con)
for (i in seq(along=col.gal.nb))
  writeLines(paste(i, paste(col.gal.nb[[i]], collapse=" ")), con=con)
close(con)
file.show(tf)

read.gal() and write.nb.gal() handle settings in which the observations 
have IDs which are not necessarily the integers 1:n, and do sanity 
checking.

Hope this helps,

Roger