[R-sig-Geo] Help converting neighbor list to vector
Corey Sparks
corey.sparks at utsa.edu
Wed Jun 23 14:04:19 CEST 2010
Hello all,
I have a neighbor list, formed from poly2nb in spdep, and a spatial
weight matrix formed by nbmat(). I then extract all of the elements of
the matrix that are nonzero (the neighbors for each observation),
here's what i've done
sa<-readShapePoly("~/Documents/data/SA_bg_ses_wtabc_crime.shp")
sa.nb<-poly2nb(sa2)
sa.wt<-nb2mat(sa.nb, style="B")
x<-apply(sa.wt, 1,function(x){which(x==1)})
so, here is a preview of the x object from above:
x[1:3]
$`0`
[1] 4 11
$`1`
[1] 3 10 12
$`2`
[1] 2 7 10 12 13
If we look at the entire dataset (there are ~900 observations) the
maximum number of neighbors is 10. I would like to turn this 'x'
object into a vector of form:
row1 obs# obs#offirstneighbor obs#ofsecondeighbor
obs#ofthirdneighbor ... total#ofneighbors
like this example
V1 V2 V3 V4 V5 V6
1 1 11 2 0 0 2
2 2 12 1 3 0 3
3 3 13 2 4 0 3
Here's what I've tried, but alas it fails
nbs<-matrix(0, nrow=dim(slot(sa,"data.frame"))[1], ncol=10)
for(i in 1:dim(slot(sa,"data.frame"))[1]) { for (j in length(x[[j]]))
{nbs[i,j]<-x[[i]][j]}}
I've also tried unlist(x), but that doesn't give the result i'm
looking for. If anyone might have an idea on this one I'd really be
appreciative, and i'd be happy to make the data available if anyone
would like.
Best,
Corey
Corey Sparks
Assistant Professor
Department of Demography and Organization Studies
College of Public Policy
501 West Durango Blvd
Monterrey Building 2.270C
San Antonio, TX 78207
corey.sparks 'at' utsa.edu
210 458 3166
More information about the R-sig-Geo
mailing list