我希望围绕所有1
和0
创建集群。与Mindsweeper相似,我想基本上在所有1
周围“画一个圆”,并在存在0
的地方创建边框。
我尝试使用hclust()
并创建一个距离矩阵,但是我正在使用的实际表非常大,并且运行时遇到了问题。
test_matrix <- matrix(c( 1,1,0,0,0,0,1,
1,1,1,0,0,1,0,
0,1,0,0,0,1,0,
0,0,0,1,1,1,0,
0,0,0,1,1,1,1),nrow=5)
结果如下:
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 1 0 0 1 0 1 0
[2,] 1 1 0 0 0 1 1
[3,] 0 1 1 0 0 0 1
[4,] 0 1 0 0 0 0 1
[5,] 0 1 0 1 1 0 1
我的规则如下:如果通过上,下,左,右,对角线(任何方向)将任何1
连接到任何1
,请继续扩展“集群”。基于这些规则(每个点有8个连接点),我可以发现四个具有孤立的1
的唯一集群。
您将如何编码以找到这些组?
答案 0 :(得分:9)
我认为在这里群集是正确的方法,但是您为该任务选择了一种较差的方法(计算量大)。我会像这样去DBSCAN:
library(dbscan)
## slightly altered test matrix to include a "cluster" with a single 1
test_matrix <- matrix(c( 1,1,0,0,0,0,1,
1,1,1,0,0,1,0,
0,1,0,0,0,1,0,
0,0,0,1,1,1,0,
1,0,0,1,1,1,1),
nrow=5, byrow = TRUE)
## find rows and columns of 1s
ones_pos <- which(test_matrix > 0,arr.ind=TRUE)
## perform DBSCAN clustering
## setting eps = sqrt(2) + .1 corresponds to your neighbourhood definition
## setting minPts = 2 will mark clusters of one point as noise
clust <- dbscan(ones_pos, eps = sqrt(2), minPts = 2)
## find the indices of noise elements
singular_ones <- ones_pos[clust$cluster == 0, ]
singular_ones
#> row col
#> 5 1
要查找所有群集(包括仅由一个1组成的群集),只需将minPts
设置为1。在这种情况下,不会产生噪音。群集成员身份存储在clust$cluster
中。
我敢肯定,这种方法对于大型矩阵也将很快。