获取R中的连通分量
我有一个值为0或1的矩阵,我想获得相邻1的组的列表 例如,矩阵获取R中的连通分量,r,graph-algorithm,connected-components,R,Graph Algorithm,Connected Components,我有一个值为0或1的矩阵,我想获得相邻1的组的列表 例如,矩阵 mat = rbind(c(1,0,0,0,0), c(1,0,0,1,0), c(0,0,1,0,0), c(0,0,0,0,0), c(1,1,1,1,1)) > mat [,1] [,2] [,3] [,4] [,5] [1,] 1 0 0 0 0 [2,] 1 0
mat = rbind(c(1,0,0,0,0),
c(1,0,0,1,0),
c(0,0,1,0,0),
c(0,0,0,0,0),
c(1,1,1,1,1))
> mat
[,1] [,2] [,3] [,4] [,5]
[1,] 1 0 0 0 0
[2,] 1 0 0 1 0
[3,] 0 0 1 0 0
[4,] 0 0 0 0 0
[5,] 1 1 1 1 1
应返回以下4个连接部件:
C1={(1,1);(2,1)}
C2={(2,4)}
C3={(3,3)}
C4={(5,1);(5,2);(5,3);(5,4);(5,5)}
有人知道如何在R中快速完成吗?我的真实矩阵确实相当大,如2000x2000(但我希望连接的组件数量相当小,即200)。通过更新,您可以将二进制矩阵转换为光栅对象,并使用clumps函数。然后就是数据管理,返回您想要的确切格式。示例如下:
library(igraph)
library(raster)
mat = rbind(c(1,0,0,0,0),
c(1,0,0,1,0),
c(0,0,1,0,0),
c(0,0,0,0,0),
c(1,1,1,1,1))
Rmat <- raster(mat)
Clumps <- as.matrix(clump(Rmat, directions=4))
#turn the clumps into a list
tot <- max(Clumps, na.rm=TRUE)
res <- vector("list",tot)
for (i in 1:tot){
res[i] <- list(which(Clumps == i, arr.ind = TRUE))
}
如果有更好的方法从光栅对象到最终目标,我不会感到惊讶。同样,2000年到2000年的矩阵对于这一点来说也不是什么大问题
旧的(错误的答案),但对于想要图形的连接组件的人来说应该很有用 您可以使用igraph包将邻接矩阵转换为网络并返回组件。您的示例图形是一个组件,因此我删除了一条边以进行说明
library(igraph)
mat = rbind(c(1,0,0,0,0),
c(1,0,0,1,0),
c(0,0,1,0,0),
c(0,0,0,0,0),
c(1,1,1,1,1))
g <- graph.adjacency(mat) %>% delete_edges("5|3")
plot(g)
clu <- components(g)
groups(clu)
根据我的经验,这个算法非常快,所以我认为2000到2000年不会是一个问题。谢谢你的回答,但我的矩阵不是邻接矩阵:它不表示图形。我想找到1的分组(即矩阵中的adacent)。啊,对不起-
连接的组件
是我描述的一个术语。光栅软件包似乎有一个名为clump
的函数,可以满足您的需要。我看看能不能举个例子。太好了!(i in 1:max(Clumps,na.rm=TRUE))的循环可以简化为(i in 1:tot)
,不是吗?
library(igraph)
mat = rbind(c(1,0,0,0,0),
c(1,0,0,1,0),
c(0,0,1,0,0),
c(0,0,0,0,0),
c(1,1,1,1,1))
g <- graph.adjacency(mat) %>% delete_edges("5|3")
plot(g)
clu <- components(g)
groups(clu)
> groups(clu)
$`1`
[1] 1 2 4 5
$`2`
[1] 3