mjo
mjo

Reputation: 1

Heatmap in R grouped by a specific column of a dataframe

I have a dataframe with ~100 columns and ~900 rows from which I want to generate a heatmap. I want to group rows by 1 column (Grouping Factor), to have 3 groups (A,B,C) (showing the mean of each group) and I also need to scale the data. I have an example table below.

Grouping Factor Var1 Var2 Var3
A 1.2 1.3 1.4
B 1.3 0.6 1.5
C 0.8 1.1 1.6
C 1.5 0.4 1.2
C 0.6 0.9 1.3
A 1.0 1.5 1.6
B 0.7 0.6 1.7
B 1.1 0.2 1.9
A 1.5 1.5 0.1

I have not been able to group the data by the grouping factor

Upvotes: 0

Views: 414

Answers (1)

Andre Wildberg
Andre Wildberg

Reputation: 19088

A row-wise scaled heatmap grouped by the first column

First generate a matrix with row names in the right order

mat <- as.matrix(df[order(df$Grouping.Factor),-1])
rownames(mat) <- df[order(df$Grouping.Factor),1]

then plot without clustering

heatmap(mat[nrow(mat):1,], Rowv=NA, Colv=NA)

Data

df <- structure(list(Grouping.Factor = c("A", "B", "C", "C", "C", "A", 
"B", "B", "A"), Var1 = c(1.2, 1.3, 0.8, 1.5, 0.6, 1, 0.7, 1.1, 
1.5), Var2 = c(1.3, 0.6, 1.1, 0.4, 0.9, 1.5, 0.6, 0.2, 1.5), 
    Var3 = c(1.4, 1.5, 1.6, 1.2, 1.3, 1.6, 1.7, 1.9, 0.1)), 
class = "data.frame", row.names = c(NA, -9L))

heatmap plot

Upvotes: 0

Related Questions