基于不同矩阵相似性的层次聚类

时间:2012-10-17 06:03:04

标签: r matrix

  

可能重复:
  How to apply a hierarchical or k-means cluster analysis using R?

考虑具有相同列数但行数不同的这四个矩阵

library(gtools)

m1 <- matrix(sample(c(-1, 0, 1), 15, replace=T), 3)
m2 <- matrix(sample(c(-1, 0, 1), 25, replace=T), 5)
m3 <- matrix(sample(c(-1, 0, 1), 25, replace=T), 5)
m4 <- matrix(sample(c(-1, 0, 1), 30, replace=T), 6)   
rownames(m1) <- c(1:3)
rownames(m2) <- c(4:8)
rownames(m3) <- c(9:13)
rownames(m4) <- c(14:19)

我希望在按以下格式排列时将hclust()应用于这四个矩阵:

mat <- list(m1, m2, m3, m4)

unite <- rbind(m1,m2,m3, m4)
rownames(unite) <- c(1:19)
distUnite <- as.matrix(dist(unite, method="manhattan"))

## empty matrix for storing the distance between pairwise matrices
dist4m <- matrix(0, nrow=4, ncol=4)
indices <- combinations(4,2)
distance <- apply(indices, 1,
                  function(pair){
                      print(pair)
                      s1=pair[1]
                      s2=pair[2] 
                      pairmean <- mean(distReads[which(m$Sample==samples[s1]), which(m$Sample==samples[s2])])

                      dist4m[s1,s2] <<- pairmean
                      dist4m[s2,s1] <<- pairmean
                  })

print(dist4m)
## then use hclust(), and plot()     

上面的脚本应该可以工作,但我想知道是否有更有效和可靠的方法来解决?

感谢您的建议。

1 个答案:

答案 0 :(得分:5)

对它们进行分组(我假设你想要cbind和fill):

m.list <- list(m1,m2,m3,m4)
n <- max(sapply(m.list, nrow))
m.all <- do.call(cbind, lapply(m.list, function (x)
rbind(x, matrix(, n-nrow(x), ncol(x))))) 

m.dist <- dist(m.all)
m.hclust <- hclust(m.dist)
plot(m.hclust)

enter image description here

单独:

m1 <- matrix(sample(c(-1, 0, 1), 15, replace=T), 3) 
m2 <- matrix(sample(c(-1, 0, 1), 25, replace=T), 5)
m3 <- matrix(sample(c(-1, 0, 1), 25, replace=T), 5)
m4 <- matrix(sample(c(-1, 0, 1), 30, replace=T), 6)

m1.dist <- dist(m1)
m2.dist <- dist(m2)
m3.dist <- dist(m3)
m4.dist <- dist(m4)

m1.hclust <- hclust(m1.dist)
m2.hclust <- hclust(m2.dist)
m3.hclust <- hclust(m3.dist)
m4.hclust <- hclust(m4.dist)

plot(m1.hclust)
plot(m2.hclust)
plot(m3.hclust)
plot(m4.hclust)

enter image description here enter image description here enter image description here enter image description here