0

I have been trying to figure out how to create an empty adjacency matrix form the given function:

AdjDist <- function(distMatrix, dist){}

Everything I have tried does not work. Is there anyone who can help with this? (the distance matrix is 5x5 if that helps.)

  • Welcome to StackOverflow. Please take a look at these tips on how to produce a [minimum, complete, and verifiable example](http://stackoverflow.com/help/mcve), as well as this post on [creating a great example in R](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Perhaps the following tips on [asking a good question](http://stackoverflow.com/help/how-to-ask) may also be worth a read. – lmo Sep 12 '16 at 17:28
  • 2
    Your code does not make sense. For one, an 'empty adjacency matrix' is just an empty matrix. Second, ``function`` is not a command. Third, where did you get ``distMatrix`` from? All these suggest you need to start with baby steps with R before moving on to creating matrices... – Cyrus Mohammadian Sep 12 '16 at 17:28
  • 1
    A distance matrix is a *dense* matrix where each element is the distance between an object indexed by the row and an object indexed by the column. An adjacency matrix is *sparse* in the sense that only adjacent objects (i.e., in a graph) have an element that is non-zero. So, what is the criterion for adjacency that you have that is a function of the distance? – aichao Sep 12 '16 at 17:48

1 Answers1

1

It is not at all clear as to what you are after and please do follow the advice on how to ask a complete, reproducible question. An "empty adjacency matrix" is a bit of a non sequitur and does hint at a novice understanding of R.

You can easily perform a adjacency analysis using spdep. Hopefully this is close to what you are after.

First, load libraries and example data (meuse from sp library)

library(sp)
library(spdep)
data(meuse)
coordinates(meuse) <- ~x+y

Now we create a neighbor object and look at the first six observations of the neighbor matrix with the associated four neighbors. The row number corresponds to the row number of meuse and each column is the row index of the nearest neighbor.

meuse.knn <- knearneigh(coordinates(meuse), k=4)
  head(meuse.knn$nn)

We can plot the linkages of k=4 using a graph structure

plot(meuse, pch=19)
 plot(knn2nb(meuse.knn), coordinates(meuse), add=TRUE)
   title(main="K nearest neighbours, k=4")

Now, for illustration purposes, we can subset the fifth observation in meuse and it's associated (k=4) nearest observations.

nn1.ids <- as.vector(meuse.knn$nn[5,])             
nn1 <- meuse[nn1.ids,]

And then plot the fifth observation in meuse with its 4 nearest neighbors.

plot(nn1, pch=19, col="red")    
plot(meuse[5,], pch=19, col="black", add=TRUE) 

The actual adjacency matrix is contained in the knearneigh object (x$nn).

Jeffrey Evans
  • 2,325
  • 12
  • 18