title: How to create adjacency matrix from grid coordinates in R?
body: <p>I'm new to this site. I was wondering if anyone had experience with turning a list of grid coordinates (shown in example code below as df). I've written a function that can handle the job for very small data sets but the run time increases exponentially as the size of the data set increases (I think 800 pixels would take about 25 hours). It's because of the nested for loops but I don't know how to get around it.</p>
  
  <pre><code>## Dummy Data
  x &lt;- c(1,1,2,2,2,3,3)
  y &lt;- c(3,4,2,3,4,1,2)
  df &lt;- as.data.frame(cbind(x,y))
  df
  
  ## Here's what it looks like as an image
  a &lt;- c(NA,NA,1,1)
  b &lt;- c(NA,1,1,1)
  c &lt;- c(1,1,NA,NA)
  image &lt;- cbind(a,b,c)
  f &lt;- function(m) t(m)[,nrow(m):1]
  image(f(image))
  
  ## Here's my adjacency matrix function that's slowwwwww
  adjacency.coordinates &lt;- function(x,y) {
    df &lt;- as.data.frame(cbind(x,y))
    colnames(df) = c("V1","V2")
    df &lt;- df[with(df,order(V1,V2)),]
    adj.mat &lt;- diag(1,dim(df)[1])
    for (i in 1:dim(df)[1]) {
      for (j in 1:dim(df)[1]) {
        if((df[i,1]-df[j,1]==0)&amp;(abs(df[i,2]-df[j,2])==1) | (df[i,2]-df[j,2]==0)&amp;(abs(df[i,1]-df[j,1])==1)) {
          adj.mat[i,j] = 1
        }
      }
    }
    return(adj.mat)
  }
  
  ## Here's the adjacency matrix
  adjacency.coordinates(x,y)
  </code></pre>
  
  <p>Does anyone know of a way to do this that will work well on a set of coordinates a couple thousand pixels long? I've tried conversion to SpatialGridDataFrame and went from there but it won't get the adjacency matrix correct. Thank you so much for your time.</p>