[R] dnearneigh::spdep: undesired behaviour with SpatialPoints object: bug or feature? Please confirm.

Roger Bivand roger.bivand at nhh.no
Fri Mar 21 13:50:03 CET 2014


Jan Holstein <jan.holstein <at> awi.de> writes:

> 
> I noticed that dnearneigh::spdep shows diverging behaviour with matrix and
> SpatialPoints objects respectively:
> 
> reproducible example:
> 
> library(spdep)
> set.seed(5)
> spdf<-SpatialPointsDataFrame(cbind(lon=runif(1000,2,8),lat=runif(1000,53,56)),
>          data=data.frame(par=runif(1000,0,1)),coords.nrs =
> numeric(0),proj4string=CRS("+init=epsg:4326"))

Thanks for a reproducible example; posting on R-sig-geo would have elicited
an earlier response.

This will only generate compliant behaviour when rgdal is loaded, converting
+init=epsg:4326 to +init=epsg:4326 +proj=longlat +datum=WGS84 +no_defs
+ellps=WGS84 +towgs84=0,0,0, so that is.projected(spdf) is FALSE


> 
> dnearneigh(x=coordinates(spdf), d1=0, d2=20,longlat = TRUE)
> #Neighbour list object:
> #Number of regions: 1000 
> #Number of nonzero links: 9504 
> #Percentage nonzero weights: 0.9504 
> #Average number of links: 9.504 
> #2 regions with no links:
> #449 619
> 
> but ...

There is a bug in the logic, but:

dnearneigh(as(spdf,"SpatialPoints"), 0, 20)
#Neighbour list object:
#Number of regions: 1000 
#Number of nonzero links: 9288 
#Percentage nonzero weights: 0.9288 
#Average number of links: 9.288 

which was the intention - either provide an object inheriting from
SpatialPoints, with longlat set internally, or set it manually. Following
the removal of the logic bug:

dnearneigh(as(spdf,"SpatialPoints"), 0, 20, longlat = TRUE)
#Neighbour list object:
#Number of regions: 1000 
#Number of nonzero links: 9288 
#Percentage nonzero weights: 0.9288 
#Average number of links: 9.288 
#Warning message:
#In dnearneigh(as(spdf, "SpatialPoints"), 0, 20, longlat = TRUE) :
#  dnearneigh: longlat overriden for Spatial object

Coercion to SpatialPoints isn't needed - the function looks for objects
inheriting from SpatialPoints, so just spdf is sufficient.

Bugfix on R-forge at revision 552.

Roger


> dnearneigh(as(spdf,"SpatialPoints"), 0, 20,longlat = TRUE)
> #Neighbour list object:
> #Number of regions: 1000 
> #Number of nonzero links: 999000 
> #Percentage nonzero weights: 99.9 
> #Average number of links: 999 
> 
> it seems that 'dnearneigh' ignores longlat=TRUE if class(x)==SpatialPoints,
> since
> 
> dnearneigh(x=coordinates(spdf), d1=0, d2=20,longlat = FALSE)
> #Neighbour list object:
> #Number of regions: 1000 
> #Number of nonzero links: 999000 
> #Percentage nonzero weights: 99.9 
> #Average number of links: 999
> 
> gives the same 'undesired' result. 
> 

> -----
> Jan M. Holstein, Dept. Functional Ecology, Alfred Wegener Institut for
Polar and Marine Research (AWI)
> --

>




More information about the R-help mailing list