Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cluster binary matrix in R

Tags:

r

matrix

I have a binary matrix between 2 variables. I would like to know if there is a way to cluster the binary matrix in R. If so, which algorithm should I be using?

The matrix looks like this

        hobby1  hobby2  hobby3  hobby4
person1   1       0       0       1
person2   0       1       0       1
person3   1       1       1       0
person4   0       1       1       1

So clustering those persons by the most common hobbies they have. What is the best method to do it?

Thanks

like image 311
user1375640 Avatar asked Sep 09 '26 07:09

user1375640


1 Answers

How about crossprod() and reshape2::melt():

# CREATE THE MATRIX
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))  

enter image description here

like image 115
Troy Avatar answered Sep 11 '26 21:09

Troy