R M个数据点上N个聚类实验矩阵的共现总数

R M个数据点上N个聚类实验矩阵的共现总数,r,vectorization,R,Vectorization,我有一个矩阵,其中每一行都是聚类算法的输出。例如,通过3个实验、7个数据点和4个可能的聚类,它可能是: # 1 2 1 2 2 3 3 # output of first clustering. Numbers are cluster labels # 1 2 1 2 3 4 4 # output of second clustering # 2 1 2 3 2 1 1 # output of third clustering 我知道如何创建一个共现矩阵,以判断两个点是否位于同一簇中: xp

我有一个矩阵,其中每一行都是聚类算法的输出。例如,通过3个实验、7个数据点和4个可能的聚类,它可能是:

# 1 2 1 2 2 3 3 # output of first clustering. Numbers are cluster labels
# 1 2 1 2 3 4 4 # output of second clustering
# 2 1 2 3 2 1 1 # output of third clustering
我知道如何创建一个共现矩阵,以判断两个点是否位于同一簇中:

xp <- c(1, 2, 1, 2, 2, 3, 3)
pairwise <- apply(as.matrix(xp), 1, 
                 function(x) as.numeric(x==as.matrix(xp)))
xp
apply(t(cluster.assignments[i,])、2、函数(x)as.numeric(x==cluster.assignments[i,])
相当于
sapply(cluster.assignments[i,]、“==”、cluster.assignments[i,])
outer(cluster.assignments[i,]、cluster.assignments[i,]、“==”
,这可能有点效率。由于要比较每一对列,您可以将每一列视为一个元素,并使用类似于
do.call(rbind、lappy(seq_len(ncol(cluster.assignments))、函数(j)colSums(cluster.assignments[,j]==cluster.assignments))
的方法进行一些调整,以避免对相同的列对进行两次相等测试。
# toy data
cluster.assignments <- t(replicate(100,sample(10, replace=TRUE)))

n_samples <- dim(cluster.assignments)[1]
n_dim <- dim(cluster.assignments)[2]
pairwise <- matrix(0, n_dim, n_dim)
for(i in 1:n_samples){
    pairwise <- pairwise + 
        apply(t(cluster.assignments[i,]), 2, 
              function(x) as.numeric(x==cluster.assignments[i,]))
}

pairwise