[R-sig-Geo] spdep: making nb object from csv data

Roger Bivand Roger.Bivand at nhh.no
Fri Mar 26 20:04:55 CET 2010


On Fri, 26 Mar 2010, Philip A. Viton wrote:

>
> Suppose I have a data frame with a bunch of spatial data
> indexed by a region.id, say r_id. I also have a csv file
> with spatial neighbors whose format is: row 1 = labels;
> column 1 = region id whose order is different from r_id, and
> the rest is a square 0/1 indicator matrix of spatial neighbors.
>
> How can I import the csv data into R as an nb object, so
> that the order matches the region order in the dataframe?
> (I suppose it would be fairly easy to use the data in the csv file
> to construct a gal file and then use read.gal;
> but I'm hoping there's a more straightforward way).

I guess it is easier not to randomise the ids, but I think that we can get 
the fish out of this fish soup.

First read the csv file (into a data frame). Most likely the column 
headers will be taken as col.names, with the first column the row names. 
Check that the r_id match the column names, and the values in the first 
column. Use match() to do this, and examine the length of the output and 
its contents. If it looks OK, use the output of match to re-order the 
matrix created by dropping the first column of the csv data.frame and 
coercing with as.matrix().

If:

o <- match(r_id, col_nms)
m <- as.matrix(csv_df[, -1])
m1 <- m[o, o]

then mat2listw(m1)

should be what you need. However, do check everything twice, including the 
order of the arguments to match() - I always have to as they feel 
counter-intuitive. If you have some centroid coordinates in the data 
frame, use them with the plot method for nb objects to double-check.

Hope this helps,

Roger

>
> Thanks!
>
> ------------------------
> Philip A. Viton
> City Planning, Ohio State University
> 275 West Woodruff Avenue, Columbus OH 43210
> viton.1 at osu.edu
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at stat.math.ethz.ch
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>

-- 
Roger Bivand
Economic Geography Section, Department of Economics, Norwegian School of
Economics and Business Administration, 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