Difference between revisions of "Cluster.R"

From Organic Design wiki
(image plot)
(# {{R}})
 
(7 intermediate revisions by the same user not shown)
Line 1: Line 1:
clusterPlot <- function(x, dmethod = "euclidian", hmethod="complete", ...) {
+
# {{R}}
 +
clusterPlot <- function(x, rowNames = NULL, dmethod = "euclidian", hmethod="complete", ...) {
 
   oldpar <- par(mfrow=c(2,1))   
 
   oldpar <- par(mfrow=c(2,1))   
 +
 +
  if(is.character(rowNames) & (length(rowNames) == nrow(x))) {
 +
    rownames(x) <- rowNames
 +
  }
 
   xDist <- dist(x, method=dmethod)
 
   xDist <- dist(x, method=dmethod)
 
    
 
    
 
# 1) Tree dendrogram
 
# 1) Tree dendrogram
   xClust <- hclust(xDist)
+
   xClust <- hclust(xDist, method=hmethod)
   plclust(xDist)
+
   plclust(xClust, sub="")
 
    
 
    
 
# 2) Image plot...   
 
# 2) Image plot...   
   image(x = 1:nrow(x), y = 1:ncol(x) z = x[xClust$order, ])
+
   image(x = 1:nrow(x), y = 1:ncol(x), z = x[xClust$order, ], col=heat.colors(nrow(x)), ...)
 
   par(oldpar)
 
   par(oldpar)
 
   invisible()
 
   invisible()
 
}
 
}
 +
 +
# Euclidian distance
 +
X <- matrix(1:9, nc=3)
 +
X1 <- X[1,]
 +
X2 <- X[2,]
 +
 +
dist(X)
 +
sqrt(sum((X1-X2)^2))
 +
 +
# Example
 +
x <- matrix(rnorm(40), nc=4)
 +
colnames(x) <- LETTERS[1:4]
 +
rownames(x) <- letters[1:10]
 +
clusterPlot(x)
 +
clusterPlot(x, rowNames = LETTERS[1:10])

Latest revision as of 19:46, 4 November 2007

Code snipits and programs written in R, S or S-PLUS clusterPlot <- function(x, rowNames = NULL, dmethod = "euclidian", hmethod="complete", ...) {

 oldpar <- par(mfrow=c(2,1))  
 if(is.character(rowNames) & (length(rowNames) == nrow(x))) {
   rownames(x) <- rowNames
 }
 xDist <- dist(x, method=dmethod)
 
  1. 1) Tree dendrogram
 xClust <- hclust(xDist, method=hmethod)
 plclust(xClust, sub="")
 
  1. 2) Image plot...
 image(x = 1:nrow(x), y = 1:ncol(x), z = x[xClust$order, ], col=heat.colors(nrow(x)), ...)
 par(oldpar)
 invisible()

}

  1. Euclidian distance

X <- matrix(1:9, nc=3) X1 <- X[1,] X2 <- X[2,]

dist(X) sqrt(sum((X1-X2)^2))

  1. Example

x <- matrix(rnorm(40), nc=4) colnames(x) <- LETTERS[1:4] rownames(x) <- letters[1:10] clusterPlot(x) clusterPlot(x, rowNames = LETTERS[1:10])