Clustering using Correlation as Distance Measures in R



Clustering using Correlation as Distance Measures in R

Different distance measures are available for clustering analysis. This article describes how to perform clustering in R using correlation as distance metrics.



Contents:

Prerequisites

The following R packages will be used:

  • pheatmap [pheatmap package]: Creates pretty heatmaps.
  • heatmap.2() [gplots package]: Another alternative for drawing heatmaps.

Demo data

Generate a demo dataset:

set.seed(123)
mydata <- matrix(rnorm(200), 20, 10)
mydata[1:10, seq(1, 10, 2)] = mydata[1:10, seq(1, 10, 2)] + 3
mydata[11:20, seq(2, 10, 2)] = mydata[11:20, seq(2, 10, 2)] + 2
mydata[15:20, seq(2, 10, 2)] = mydata[15:20, seq(2, 10, 2)] + 4
colnames(mydata) = paste("Sple", 1:10, sep = "")
rownames(mydata) = paste("Gene", 1:20, sep = "")
head(mydata[, 1:4], 4)
##       Sple1  Sple2 Sple3  Sple4
## Gene1  2.44 -1.068  2.31  0.380
## Gene2  2.77 -0.218  2.79 -0.502
## Gene3  4.56 -1.026  1.73 -0.333
## Gene4  3.07 -0.729  5.17 -1.019

Prepare your data as described at : Data Preparation and R Packages for Cluster Analysis

Draw heatmaps using pheatmap

The default is to use the euclidean distance as dissimilarity measure.

library("pheatmap")
pheatmap(mydata, scale = "row")

Use correlation as dissimilarity measures:

# Pairwise correlation between samples (columns)
cols.cor <- cor(mydata, use = "pairwise.complete.obs", method = "pearson")
# Pairwise correlation between rows (genes)
rows.cor <- cor(t(mydata), use = "pairwise.complete.obs", method = "pearson")

# Plot the heatmap
library("pheatmap")
pheatmap(
  mydata, scale = "row", 
  clustering_distance_cols = as.dist(1 - cols.cor),
  clustering_distance_rows = as.dist(1 - rows.cor)
  )

Draw heatmaps using gplots

Default heatmap using the euclidean distance as dissimilarity measure.

library("gplots")
heatmap.2(mydata, scale = "row", col = bluered(100), 
          trace = "none", density.info = "none")

Use correlation as dissimilarity measures:

# Pairwise correlation between samples (columns)
cols.cor <- cor(mydata, use = "pairwise.complete.obs", method = "pearson")
# Pairwise correlation between rows (genes)
rows.cor <- cor(t(mydata), use = "pairwise.complete.obs", method = "pearson")

## Row- and column-wise clustering using correlation 
hclust.col <- hclust(as.dist(1-cols.cor)) 
hclust.row <- hclust(as.dist(1-rows.cor))


# Plot the heatmap
library("gplots")
heatmap.2(mydata, scale = "row", col = bluered(100), 
          trace = "none", density.info = "none",
          Colv = as.dendrogram(hclust.col),
          Rowv = as.dendrogram(hclust.row)
          )

Summary

In this article we introduce how perform clustering analysis and draw heatmaps in R using the pheatmap and the gplots package



Version: Français





No Comments

Give a comment

Want to post an issue with R? If yes, please make sure you have read this: How to Include Reproducible R Script Examples in Datanovia Comments