我在两个变量之间有一个二进制矩阵。我想知道在R中是否有对二进制矩阵进行聚类的方法,如果是,我应该使用哪种算法?
矩阵看起来像这样
hobby1 hobby2 hobby3 hobby4
person1 1 0 0 1
person2 0 1 0 1
person3 1 1 1 0
person4 0 1 1 1因此,为了根据患者最常见的爱好对他们进行聚类,我在堆栈溢出问题中发现了以下代码。
m.h<-(matrix(sample(0:1,200,T),nrow=20))
# CREATE CROSS_PRODUCT
m.cross<-matrix(unlist(lapply(1:nrow(m.h),function(x)crossprod(m.h[x,],t(m.h)))),nrow=nrow(m.h),byrow=T)
# USE reshape2 to melt/flatten the data
require(reshape2)
m.long<-melt(m.cross)
m.long[order(m.long$value,factor(m.long$Var2),factor(m.long$Var1)),]
require(ggplot2)
ggplot(m.long)+
geom_tile(aes(Var1,Var2,fill=value))+
geom_text(aes(Var1,Var2,label=value))+
theme(axis.text.x = element_text(angle = 90, hjust = 1))+
scale_fill_gradient(low="yellow",high="red") +
scale_x_discrete(breaks = 1:nrow(m.h), labels=unlist(lapply(1:nrow(m.h),function(x)paste0("Person ",x)))) +
scale_y_discrete(breaks = 1:nrow(m.h), labels=unlist(lapply(1:nrow(m.h),function(x)paste0("Person ",x)))) +
coord_cartesian(xlim=c(0,nrow(m.h)+1),ylim=c(0,nrow(m.h)+1)) 然而,我想要的图形显示人在X和Y轴。为此,您有scale_y_discrete和scale_x_discrete函数,但是它不工作,我不知道为什么,因为我的结果显示为:

发布于 2022-03-18 12:25:15
正如注释中所述,您的Var是数字的,这意味着它们是连续的。因此,您应该对数据使用scale_x_continuous和scale_y_continuous。您可以使用以下代码:
m.h<-(matrix(sample(0:1,200,T),nrow=20))
# CREATE CROSS_PRODUCT
m.cross<-matrix(unlist(lapply(1:nrow(m.h),function(x)crossprod(m.h[x,],t(m.h)))),nrow=nrow(m.h),byrow=T)
# USE reshape2 to melt/flatten the data
require(reshape2)
m.long<-melt(m.cross)
m.long[order(m.long$value,factor(m.long$Var2),factor(m.long$Var1)),]
require(ggplot2)
ggplot(m.long)+
geom_tile(aes(Var1,Var2,fill=value))+
geom_text(aes(Var1,Var2,label=value))+
theme(axis.text.x = element_text(angle = 90, hjust = 1))+
scale_fill_gradient(low="yellow",high="red") +
scale_x_continuous(breaks = 1:nrow(m.h), labels=unlist(lapply(1:nrow(m.h),function(x)paste0("Person ",x)))) +
scale_y_continuous(breaks = 1:nrow(m.h), labels=unlist(lapply(1:nrow(m.h),function(x)paste0("Person ",x)))) +
coord_cartesian(xlim=c(0,nrow(m.h)+1),ylim=c(0,nrow(m.h)+1)) 输出:

https://stackoverflow.com/questions/71525794
复制相似问题