John Cocks
John Cocks

Reputation: 1

How to create an adjacency matrix from a distance matrix in R?

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.)

Upvotes: 0

Views: 1383

Answers (1)

Jeffrey Evans
Jeffrey Evans

Reputation: 2397

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).

Upvotes: 1

Related Questions