[R-sig-Geo] distance matrix to listw

Roger Bivand Roger.Bivand at nhh.no
Mon May 19 10:59:38 CEST 2008

On Mon, 19 May 2008, Michal Palenik wrote:

> dear list,
> I want to do analysis using lagsarlm function, however I am stuck on
> listw object. I have distances among spatial points in a mysql table in
> form:
> point1_id | point2_id | distance (in km)
> dataset in also in mysql table in form:
> point_id | year | variable1 | variable2 | ....
> so my questions:
> 1. how to I create a listw object from above mysql table ?

The easiest way is to do it in R, provided that the coordinates of the 
observations are stored in the same table as the data - then there is less 
danger of the IDs getting mixed up. Then you'd ceate first an nb object 
using your choice of method, adding in the (distances) in the glist= 
argument to nb2listw() - examples are given there.

> 2. if i create data frame with command
> data<-dbGetQuery(con, "select * from data");
> is it enough or some special actions need to be taken to connect data
> frame to listw object (eg so that lagsarlm knows which spatial point in
> data is which point in listw) ?

If you want to use the external table of distances (because say they are 
network distances), you can read them in as a data frame, or possibly 
write then to a text file in GWT format. If the latter, see the GeoDa site 
or read.gwt2nb() for details of the format, using the point_ID values from 
the data frame with the variables as the region.id= argument. If your 
three field table is already thresholded, this might be a good way to go 
(say distance < threshold). Note that read.gwt2nb() returns an nb oject, 
with the distances as part of the "GeoDa" attribute:

nb <- read.gwt2nb("your_three_columns", region.id=df$point_id)
dlist <- attr(nb, "GeoDa")$dist

then use nb2listw() to make the listw object (with for example the inverse 
of dlist as the glist= argument).

If you prefer to read in the data frame, convert the data frame to a 
"spatial.neighbour" object, and get back to listw with sn2listw(). This is 
untried and may not work unless point_id is a 1:n sequence, because the 
"spatial.neighbour" object expects that. Use the example to sn2listw() to 
see what happens.

Hope this helps,


> thanks in advance
> michal palenik

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