<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
  <title>spdep on JLA Data</title>
  <link>https://www.jla-data.net/tags/spdep/</link>
  <description>Recent content in spdep on JLA Data</description>
  <generator>Hugo -- gohugo.io</generator>
<language>en-us</language>
<copyright>Jindra Lacko</copyright>
<lastBuildDate>Sat, 02 Sep 2023 00:00:00 +0000</lastBuildDate>

<atom:link href="https://www.jla-data.net/tags/spdep/index.xml" rel="self" type="application/rss+xml" />


<item>
  <title>Spatial Neighborhoods</title>
  <link>https://www.jla-data.net/eng/2023-05-10-spatial-neighborhoods-in-r/</link>
  <pubDate>Sat, 02 Sep 2023 00:00:00 +0000</pubDate>
  
<guid>https://www.jla-data.net/eng/2023-05-10-spatial-neighborhoods-in-r/</guid>
  <description>


&lt;p&gt;Two important concepts in the field of spatial econometrics are contiguity matrices &lt;strong&gt;C&lt;/strong&gt; and weight matrices &lt;strong&gt;W&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Contiguity matrices provide qualitative information about which polygons are neighbors, and weight (or spatial weight) matrices give a quantitative measure of the this neighborhood relationship.&lt;/p&gt;
&lt;p&gt;In this post I provide several alternative approaches to constructing contiguity and weight matrices, with examples using the well known and much loved &lt;code&gt;nc.shp&lt;/code&gt; shapefile that ships with the &lt;code&gt;{sf}&lt;/code&gt; package.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;Both contiguity and weight matrices are implemented in the &lt;code&gt;{spdep}&lt;/code&gt; package, which is the de-facto standard approach to spatial dependence modelling in R settings.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The contiguity matrix is implemented as &lt;code&gt;nb&lt;/code&gt; (short for neighborhood) object, which is a list of indexes of objects considered neighbors (whatever that means in a given context).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The weights matrix is implemented as &lt;code&gt;listw&lt;/code&gt; object, which is a compound consisting of two items:
&lt;code&gt;neighbours&lt;/code&gt; object, which is in principle the same as a &lt;code&gt;nb&lt;/code&gt; object, and a &lt;code&gt;weights&lt;/code&gt; object, which contains the weights matrix itself.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Formally the weight matrix encodes the neighborhood structure as a &lt;em&gt;n × n&lt;/em&gt; matrix &lt;strong&gt;W&lt;/strong&gt;, where elements &lt;em&gt;w&lt;sub&gt;i,j&lt;/sub&gt;&lt;/em&gt; are the spatial weights:&lt;/p&gt;
&lt;p&gt;&lt;span class=&#34;math display&#34;&gt;\[
{\bf W} = \left(\begin{array}{ccccc}
  w_{1,1}&amp;amp;w_{1,2}&amp;amp;w_{1,3}&amp;amp;\cdots &amp;amp;w_{1,n}\\
  w_{2,1}&amp;amp;w_{2,2}&amp;amp;w_{2,3}&amp;amp;\cdots &amp;amp;w_{2,n}\\
  w_{3,1}&amp;amp;w_{3,2}&amp;amp;w_{3,3}&amp;amp;\cdots &amp;amp;w_{3,n}\\
  \vdots&amp;amp;&amp;amp;&amp;amp;\ddots&amp;amp;\\
  w_{n,1}&amp;amp;w_{n,2}&amp;amp;w_{n,3}&amp;amp;\cdots &amp;amp;w_{n,n}
  \end{array}\right)
\]&lt;/span&gt;
The weights &lt;em&gt;w&lt;sub&gt;i,j&lt;/sub&gt;&lt;/em&gt; have value of zero for polygons that are &lt;em&gt;not&lt;/em&gt; considered neighbors, and non–zero values for neighboring ones.&lt;/p&gt;
&lt;p&gt;By convention a polygon is not considered to be neighboring with itself, so the diagonal of a weights matrix is zero by definition.&lt;/p&gt;
&lt;p&gt;Also by convention the individual weights are row standardized, so that weight matrix rows sum to 1. Consequently the matrix itself sums to the number of observations &lt;em&gt;n&lt;/em&gt;. This convention is represented as &lt;code&gt;style=&#39;W&#39;&lt;/code&gt; in the framework of &lt;code&gt;{spdep}&lt;/code&gt; models (other conventions, such as standardizing all weights to unity, are possible, but less commonly used).&lt;/p&gt;
&lt;p&gt;My first step is loading required packages and the &lt;code&gt;nc.shp&lt;/code&gt; shapefile as &lt;code&gt;counties&lt;/code&gt; object. The shapefile is then projected to a feety CRS, because as an European, metric born &amp;amp; bred, I find the quaint local customs amusing.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(spdep)
library(dplyr)
library(sf)
library(ggplot2)

# NC counties as polygons - a shapefile shipped with the sf package
counties &amp;lt;- st_read(system.file(&amp;quot;shape/nc.shp&amp;quot;, package = &amp;quot;sf&amp;quot;), quiet = T) %&amp;gt;% 
  st_transform(2264) # a feety CRS, to make it more interesting :)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;My second step is preparing a convenience function &lt;code&gt;report_results()&lt;/code&gt; in order to plot a map illustrating the calculated results. It takes for argument a &lt;code&gt;listw&lt;/code&gt; object, and draws a plot of neighbors of a single county, with neighborhood weight as labels. Notice that the labels are placed in the centroid of the neighbor.&lt;/p&gt;
&lt;p&gt;This convenience function will be used to show differences in calculated matrices (because a graphical example is more than 1000 words, and because I dislike repeating my code).&lt;/p&gt;
&lt;p&gt;County &lt;a href=&#34;https://en.wikipedia.org/wiki/Franklin_County,_North_Carolina&#34;&gt;Franklin&lt;/a&gt; makes for a good example, because out of all the North Carolina counties it has the biggest difference between rook and queen neighborhoods (it touches neighboring counties Halifax and Johnston in single point each).&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# a convenience function; will display county Franklin &amp;amp; its neighbors
report_results &amp;lt;- function(listw_object) {

  chart_source &amp;lt;-  counties %&amp;gt;%
    # selects neigbbors of cnty Franklin (only) as polygons
    slice(purrr::pluck(listw_object$neighbours,
                       which(counties$NAME == &amp;quot;Franklin&amp;quot;))) %&amp;gt;%
    # new column of weights relative to cnty Franklin
    mutate(weight = purrr::pluck(listw_object$weights,
                               which(counties$NAME == &amp;quot;Franklin&amp;quot;))) 
 
  # draw a plot based on chart_source object 
  ggplot(data = chart_source) +
    geom_sf() +
    geom_sf_label(aes(label = scales::percent(weight, accuracy = 1)),
                  # let&amp;#39;s use the label to mark county centroid!
                  fun.geometry = sf::st_centroid) +
    # centroid of cnty Franklin, for reference
    geom_sf(data = st_centroid(counties[which(counties$NAME == &amp;quot;Franklin&amp;quot;), ]), 
            color= &amp;quot;red&amp;quot;, pch = 4) +
    theme_void()
  
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The first example is creating a queen style neighborhood, in which neighbors are defined as polygons (counties) sharing at least a single point. In this framework county Franklin has 7 neighbors, giving each equal 14% neighborhood weight (where 14.29% = 100 / 7).&lt;/p&gt;
&lt;p&gt;The call to invoke queen neighborhoods is &lt;code&gt;spdep::poly2nb()&lt;/code&gt; with queen argument set to &lt;code&gt;TRUE&lt;/code&gt; (which is the default).&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;queen_hoods &amp;lt;- st_geometry(counties) %&amp;gt;% 
  poly2nb(queen = TRUE) %&amp;gt;% 
  nb2listw() 

report_results(queen_hoods)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://www.jla-data.net/eng/2023-05-10-spatial-neighborhoods-in-r/index_files/figure-html/queen-1.png&#34; width=&#34;100%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;The second approach is creating a rook style neighborhood, in which neighbors are defined as polygons (counties) sharing an edge – a single point is not enough. In this framework county Franklin has 5 neighbors, giving each weight of 20%.&lt;/p&gt;
&lt;p&gt;In practice, when dealing with polygons that originated from a sufficiently random process – such as admin areas that originated “bottom up” in a long settled area – you will find very few, if any, differences between queen and rook neighbors. Cases such as the famous &lt;a href=&#34;https://en.wikipedia.org/wiki/Four_Corners_Monument&#34;&gt;four corners point&lt;/a&gt; between Utah, Arizona, Colorado and New Mexico are rather rare, occurring chiefly in “top down” driven administration of newly settled territories; a fine example being the &lt;a href=&#34;https://en.wikipedia.org/wiki/List_of_counties_in_Iowa&#34;&gt;US State of Iowa&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;I confess that I had to cheat a bit using &lt;code&gt;setdiff()&lt;/code&gt; on the two &lt;code&gt;nb&lt;/code&gt; objects to find a sufficiently salient example in a mostly organically settled state of North Carolina, as I really wanted to stick with the &lt;code&gt;nc.shp&lt;/code&gt; shapefile we all know and love.&lt;/p&gt;
&lt;p&gt;The call to invoke rook neighborhoods is &lt;code&gt;spdep::poly2nb()&lt;/code&gt; with queen argument set to &lt;code&gt;FALSE&lt;/code&gt; (meaning a rook is the &lt;em&gt;not&lt;/em&gt; queenly approach).&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;rook_hoods &amp;lt;- st_geometry(counties) %&amp;gt;% 
  poly2nb(queen = FALSE) %&amp;gt;% # not queen means rook
  nb2listw() 

report_results(rook_hoods)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://www.jla-data.net/eng/2023-05-10-spatial-neighborhoods-in-r/index_files/figure-html/rook-1.png&#34; width=&#34;100%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Third approach is basing neighborhoods on K nearest neighbors. This approach is not defined for polygons (for good reasons) but a good practice for point data.&lt;/p&gt;
&lt;p&gt;In order to make it work for polygons these have to be first converted to points via &lt;code&gt;sf::st_centroid()&lt;/code&gt;. In this framework county Franklin (and every other, by definition) has 3 neighbors, giving each weight of 33%.&lt;/p&gt;
&lt;p&gt;The call to invoke KNN neighbors is &lt;code&gt;spdep::knearneigh()&lt;/code&gt;, where argument &lt;code&gt;k&lt;/code&gt; is the desired number of neighbors.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;knn_hoods &amp;lt;- st_geometry(counties) %&amp;gt;% 
  st_centroid() %&amp;gt;% # polygons to points
  knearneigh(k = 3) %&amp;gt;% # always 3 neighbors - never more, never less...
  knn2nb() %&amp;gt;% 
  nb2listw() 

report_results(knn_hoods)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://www.jla-data.net/eng/2023-05-10-spatial-neighborhoods-in-r/index_files/figure-html/knn-1.png&#34; width=&#34;100%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Fourth approach is basing neighborhoods on distance. This approach is again defined for points only, so in order to use it we have to convert our polygons to centroids.&lt;/p&gt;
&lt;p&gt;In this framework we have to set the minimum (usually zero) and maximum distance; I am using 50 miles as maximum distance between county centroids to be considered “neighboring”.&lt;/p&gt;
&lt;p&gt;In this framework county Franklin has 12 neighbors, giving each 8% weight (where 8.33% = 100 / 12).&lt;/p&gt;
&lt;p&gt;The call to invoke distance based neighbors is &lt;code&gt;spdep::dnearneigh()&lt;/code&gt;, where argument &lt;code&gt;d1&lt;/code&gt; is the minimal, and &lt;code&gt;d2&lt;/code&gt; the maximal distance.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;distance_hoods &amp;lt;- st_geometry(counties) %&amp;gt;% 
  st_centroid() %&amp;gt;% # polygon to points
  dnearneigh(d1 = 0, # from zero...
             d2 = 5280 * 50) %&amp;gt;% # ... to 50 miles
  nb2listw() 

report_results(distance_hoods) &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://www.jla-data.net/eng/2023-05-10-spatial-neighborhoods-in-r/index_files/figure-html/distance-1.png&#34; width=&#34;100%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Important fine tuning technique is altering the weights of your &lt;code&gt;listw&lt;/code&gt; object. Depending on your use case it may be – and may &lt;em&gt;not&lt;/em&gt; be – appropriate to give each neighbor equal weight, such as the 8% used in the last example. Or there may be a compelling reason to make some neighbors less equal than others.&lt;/p&gt;
&lt;p&gt;Fortunately, the &lt;code&gt;weights&lt;/code&gt; element of your &lt;code&gt;listw&lt;/code&gt; object can be easily rewritten as your situation requires.&lt;/p&gt;
&lt;p&gt;A common approach is to apply inverse distance weighting, giving more prominence to close neighbors and less to far off ones. Note how the weight of close neighbors moves from 8% to 13%, and drops to 5% for the farthest one.&lt;/p&gt;
&lt;p&gt;For this frequent use case we can leverage the &lt;code&gt;spdep::nbdists()&lt;/code&gt; function that calculates distances between elements of a &lt;code&gt;nb&lt;/code&gt; neighborhood object.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# start with a nb object (not yet listw)
nblist &amp;lt;- st_geometry(counties) %&amp;gt;% 
  st_centroid() %&amp;gt;% 
  dnearneigh(d1 = 0,d2 = 5280 * 50)
  
# then use the nb object to create a listw object
idw_hoods &amp;lt;- nb2listw(nblist)

# then rewrite the &amp;quot;weights&amp;quot; part of the said listw object
# using information contained in the original nb 
idw_hoods$weights &amp;lt;- nbdists(nblist, 
                             st_coordinates(st_centroid(counties))) %&amp;gt;% 
  lapply(function(x) 1/x)  %&amp;gt;% # distance inverted
  lapply(function(x) x/sum(x)) # W-style standardization 


report_results(idw_hoods)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://www.jla-data.net/eng/2023-05-10-spatial-neighborhoods-in-r/index_files/figure-html/weighted_distances-1.png&#34; width=&#34;100%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Yet more aggressive approach is basing weights on inverse of &lt;em&gt;squared&lt;/em&gt; distances; notice how the weight of Nash County increases to 20%, while the weight of Orange County drops to 3%.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;nblist &amp;lt;- st_geometry(counties) %&amp;gt;% 
  st_centroid() %&amp;gt;% 
  dnearneigh(d1 = 0,d2 = 5280 * 50)

idwsq_hoods &amp;lt;- nb2listw(nblist)

# again, rewrite the existing weights part of listw object
idwsq_hoods$weights &amp;lt;- nbdists(nblist, 
                              st_coordinates(st_centroid(counties))) %&amp;gt;% 
  lapply(function(x) 1/(x^2)) %&amp;gt;% # square of distance inverted
  lapply(function(x) x/sum(x)) # W-style standardization

report_results(idwsq_hoods)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://www.jla-data.net/eng/2023-05-10-spatial-neighborhoods-in-r/index_files/figure-html/weighted_queen-1.png&#34; width=&#34;100%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;A different approach is creating weights based on the length of shared border; this requires slightly more coding, as there is no standard function to return a list of border lengths of a &lt;code&gt;nb&lt;/code&gt; set (unlike for the list of distances), but not overly so.&lt;/p&gt;
&lt;p&gt;Note how, by basing the border length weighted list on queen neighborhoods, we end up with zero weights for the “joinded in the corners” counties, effectively removing the difference between the queen and the rook neighborhood patterns.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# start with a queen style, rather than rook style nb object
# - it will make the zeroes in corners (zero length border) really stand out
nblist &amp;lt;- st_geometry(counties) %&amp;gt;% 
  poly2nb(queen = TRUE) 
  
# then create a listw object
borderline_hoods &amp;lt;- nb2listw(nblist)

# then pre-allocate a list of distances
distances &amp;lt;- vector(&amp;quot;list&amp;quot;, length(nblist))

# use i as iterator over list of distances
for (i in seq_along(distances)) {
  
  # indices of neighbors of i-th element
  neighbor_ids &amp;lt;- purrr::pluck(nblist[[i]])
  
  # shared borders of (multiple) neighbors and i-th element as a line
  distances[[i]] &amp;lt;- st_intersection(st_geometry(counties)[neighbor_ids],
                                    st_geometry(counties)[i]) %&amp;gt;% 
    st_length() %&amp;gt;% # from line as geometry to length of said line
    units::drop_units() # we want share of total, which is unitless
  
}

# apply the W style standardization
distances &amp;lt;- lapply(distances, function(x) x/sum(x)) 

# overwrite the original weights object  
borderline_hoods$weights &amp;lt;- distances 

report_results(borderline_hoods)&lt;/code&gt;&lt;/pre&gt;
&lt;img src=&#34;https://www.jla-data.net/eng/2023-05-10-spatial-neighborhoods-in-r/index_files/figure-html/borderline_distances-1.png&#34; width=&#34;100%&#34; /&gt;
&lt;hr&gt;
&lt;p&gt;I believe I have demonstrated both:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the variety of options for calculating the contiguity and weight matrices&lt;/li&gt;
&lt;li&gt;the ease of doing so within the context of &lt;code&gt;{spdep}&lt;/code&gt; package and friends&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;QED :)&lt;/p&gt;
</description>
  </item>
  
</channel>
  </rss>