[R-sig-Geo] exporting neighbor list to a text file...
Roger Bivand
Roger.Bivand at nhh.no
Thu Aug 16 18:20:41 CEST 2012
On Thu, 16 Aug 2012, Alok K Bohara, PhD wrote:
> (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:
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
>
> 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
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>
--
Roger Bivand
Department of Economics, NHH Norwegian School of Economics,
Helleveien 30, N-5045 Bergen, Norway.
voice: +47 55 95 93 55; fax +47 55 95 95 43
e-mail: Roger.Bivand at nhh.no
More information about the R-sig-Geo
mailing list