1

我有一个完全由布尔变量组成的数据集。完全像下面的转化动物数据集一样,只有更多的列。如何在R中创建聚集布尔变量的图形?

# http://stats.stackexchange.com/questions/27323/cluster-analysis-of-boolean-vectors-in-r 
library(cluster) 
head(mona(animals)[[1]]) 

    war fly ver end gro hai 
ant 0 0 0 0 1 0 
bee 0 1 0 0 1 1 
cat 1 0 1 0 0 1 
cpl 0 0 0 0 0 1 
chi 1 0 1 1 1 1 
cow 1 0 1 0 1 1 

目标是重新排列行,使得类似成员资格模式的分组更易于在视觉上进行识别。

我觉得某种聚类算法可能是要走的路,但我不确定究竟要使用什么函数或如何去精确定位它。

理想情况下,表格可以作为一种棋盘格。用阴影正方形表示每个点是真还是假。

回答

1

该解决方案使用层次聚类重新排列变量。值得注意的是,由于不相似矩阵越来越大,这不能很好地进行大量的观察。 this答案中提出了许多观察的替代算法,但我没有完全理解它,或者根据参考章节了解如何实现它。

library(cluster) 
library(reshape2) 
library(ggplot2) 

# testing that it works using the categorical animals dataset 
adData <- mona(animals)$data 

# import the data, encoded with 0s and 1s for membership 
# adData <- read.csv('adData.csv') 

# clustering based off this answer https://stats.stackexchange.com/a/48364 
# create a dissimilarity matrix 
disimilarAdData <- daisy(adData) 

# hierarchically cluster by dissimilarity 
clusteredAdData <- agnes(disimilarAdData) 

# reorder the rows by dissimilarity 
orderedAdData <- adData[clusteredAdData[[1]], ] 

# make it logical data type for better graphing 
plotData <- sapply(as.data.frame(orderedAdData), as.logical) 
row.names(plotData) <- row.names(orderedAdData) 

# plot graph using shaded rows 
# http://stackoverflow.com/questions/21316363/plot-and-fill-chessboard-like-area-and-the-similars-in-r 
ggplot(melt(plotData), aes(x=Var2, y=Var1, fill=value)) + geom_tile() 

enter image description here