简体   繁体   English

如何从R中的距离矩阵创建邻接矩阵?

[英]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){} 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.) (如果有帮助,距离矩阵为5x5。)

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. “空邻接矩阵”有点不合逻辑,确实暗示了对R的新手理解。

You can easily perform a adjacency analysis using spdep. 您可以使用spdep轻松执行邻接分析。 Hopefully this is close to what you are after. 希望这与您追求的目标接近。

First, load libraries and example data (meuse from sp library) 首先,加载库和示例数据(sp库中的鼠标)

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 我们可以使用图结构绘制k = 4的链接

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. 现在,出于说明目的,我们可以将第五个观测值作为子集进行子集化,并将其与最近的观测值(k = 4)相关联。

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. 然后绘制第5个观测值,并与它的4个最近的邻居作个比较。

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). 实际的邻接矩阵包含在knearneigh对象(x $ nn)中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM