已有距离矩阵,在进行层次聚类时,需要注意以下问题:
1、距离矩阵聚类前处理
需要使用 as.dist() 处理距离矩阵,变成内置函数可识别的数据格式,这里如果不处理可能会报如下错误:
Error in if (is.na(n) || n > 65536L) stop("size cannot be NA nor exceed 65536") :
missing value where TRUE/FALSE needed
2、距离矩阵的读取
需要设置header=T, row.names=1,使得距离矩阵是个完全由数值组成的矩阵
d<-read.table("dict.mat.xls", sep="\t", header=T, row.names=1)
若不设置,矩阵中可能会存在字符串之类的变量,在利用as.dist()处理矩阵时,会将一些字符串变量转变成NA,后续聚类时依旧会报错,例如:
Error in hclust(d1, method = "complete") :
NA/NaN/Inf in foreign function call (arg 10)
完整代码如下:
#data<-read.table("input.xls",sep="\t",header=T,row.names=1) #若无距离矩阵,可导入原始数据进行计算。
#d<-dist(data) #计算距离矩阵
#######################################################
#我们已经有距离矩阵的情况下,直接读取即可
d<-read.table("dict.mat.xls",sep="\t",header=T,row.names=1)
d1<-as.dist(d)
c<-hclust(d1,method="complete")
pdf("cluster.pdf",width=8,height=8) #聚类树展示
plot(c,hang=-1,cex=.8,main="title")
dev.off()
pdf("heatmap.pdf",width=8,height=8) #聚类热图展示
heatmap(as.matrix(d),margins = c(10, 10)) #margins设置页边距距离
dev.off()