r-spatial / spdep

Spatial Dependence: Weighting Schemes and Statistics
https://r-spatial.github.io/spdep/
122 stars 26 forks source link

nbdists returns a list where each element is length 1 #111

Closed JosiahParry closed 1 year ago

JosiahParry commented 1 year ago

I'm unsure where this issue is being derived from. Note the warning message from aggregate.

Each element of the resultant list should have 8 values since there are 8 neighbors. However, there is only 1 for each.

Note the reprex below.

Sorry I can't be more detailed I'm actually stumped!

cnts <- tigris::counties(cb = TRUE)
#> Retrieving data for the year 2020
#> 
geo <- sf::st_centroid(cnts)
#> Warning in st_centroid.sf(cnts): st_centroid assumes attributes are constant
#> over geometries of x
k = 8
ks <- spdep::knearneigh(geo, k = k)
nb <- spdep::knn2nb(ks, sym = FALSE)
spdep::nbdists(nb, geo)
#> Warning in res[has_nb] <- aggregate(s2d, by = list(card_reps), c)$x: number of
#> items to replace is not a multiple of replacement length
#> [[1]]
#> [1] 54.40652
#> 
#> [[2]]
#> [1] 73.44355
#> 
#> [[3]]
#> [1] 48.92014
#> 
#> [[4]]
#> [1] 58.74515
#> 
#> [[5]]
#> [1] 54.14526
#> . . . . . truncated for your eyes
#> 
#> attr(,"call")
#> spdep::nbdists(nb = nb, coords = geo)

Created on 2022-10-27 with reprex v2.0.2

rsbivand commented 1 year ago

With this push, I see:

> cnts <- tigris::counties(cb = TRUE)
Retrieving data for the year 2020
  |======================================================================| 100%
> geo <- sf::st_centroid(cnts)
Warning message:
In st_centroid.sf(cnts) :
  st_centroid assumes attributes are constant over geometries of x
> k = 8
> ks <- spdep::knearneigh(geo, k = k)
> nb <- spdep::knn2nb(ks, sym = FALSE)
> table(sapply(nb, length))

   8 
3234 
> table(sapply(spdep::nbdists(nb, geo), length))

   8 
3234 

There was a missing simplify=FALSE in the aggregate() call - for ragged neighbour counts a list was returned, but for knn (equal counts) a matrix where simplify= took its default TRUE value. Please check and report back, thanks again for your input!

JosiahParry commented 1 year ago

we've all been bitten by simplify = FALSE! It's fixed! Thanks :)