title: Making a list of neighbor polygons touching same border of each polygon in R
body: <p>I have a shape file that has a geospacial map of different territories. I have already loaded it into R. The CRS it has is NAD83 and the ellipse is GRS80. </p>
  
  <p>I am trying to make a list of all the territories touching the border for each territory in the map.</p>
  
  <p>When I type head(shapefile), it shows something like this:</p>
  
  <pre><code>        Territory  Year
      0   ACE        1803
      1   FAS        1814
      2   CAT        1865
      3   TAT        1834
      4   GAL        1833
      5   UBE        1877
  </code></pre>
  
  <p>I have already tried: </p>
  
  <pre><code>    gTouches(shapefile, byid = TRUE)
  </code></pre>
  
  <p>and it worked, but it is not the format I want. I have also tried</p>
  
  <pre><code>    shapefile.knn &lt;- knearneigh(coordinates(shapefile), k=7)
      plot(knn2nb(shapefile.knn), coordinates(shapefile), col="red", add=TRUE)
  </code></pre>
  
  <p>and it worked as well, but I want to find the neighboring territories that TOUCH the border for each territory and this seems to just take the nearest neighbors not dependent on if they touch the border or not. I also want to make a list of these neighboring territory names for each territory name.</p>
  
  <p>I came across this link: <a href="http://grokbase.com/t/r/r-sig-geo/072fxj7bhr/how-to-find-neighbor-polygons-and-analysis-of-their-attributes" rel="nofollow noreferrer">http://grokbase.com/t/r/r-sig-geo/072fxj7bhr/how-to-find-neighbor-polygons-and-analysis-of-their-attributes</a> </p>
  
  <p>In this link, a person was asking for something similar to what I want, so I tried the code that was shared to her to see if it will work for me, but I only got this far:</p>
  
  <pre><code>   nbs &lt;- poly2nb(as(shapefile, "SpatialPolygons"))
     wts &lt;- nb2listw(nbs, style = "W")
  </code></pre>
  
  <p>I am not sure how/what to do after this, and I'm not really even sure if it will lead me to what I want. On the website they use a lag function. I tried:</p>
  
  <pre><code>   shapefile$W_var &lt;-lag(wts, shapefile$var)
  </code></pre>
  
  <p>but it didnt work and says, "Error: <code>n</code> must be a nonnegative integer scalar, not NULL of length 0". I suspect it is because I do not have a column called "var" in my shapefile, but I am not sure what type of column they are trying to refer to. </p>
  
  <p>Any help is much appreciated, thank you!</p>