0
votes

I am trying to build a heatmap in R. I wanted to split the heatmap at specific rows. For example my matrix is as:

ID A B C

FD_1 0.3 0.2 1

FD_2 0.4 1 0.9

FD_3 0.6 0.8 0.2

FS_1 0.3 0.2 1

FS_2 0.4 1 0.9

FS_3 0.6 0.8 0.2

FS_4 0.4 1 0.9

FS_5 0.6 0.8 0.2

FE_1 0.3 0.2 1

FE_2 0.4 1 0.9

FE_3 0.6 0.8 0.2

FE_4 0.4 1 0.9

I need to make a heatmap that includes 3 slice: one for 3 FD, one for 5 FS and one for 4 FE. And label each slice with their name as FD, FS and FE.

I'm using this code: Heatmap(M_matrix, name = "level", row_split = M_matrix$ID)

But I'm getting this error: Error in M_matrix$ID : $ operator is invalid for atomic vectors

Any suggestion? Thanks

3

3 Answers

1
votes

You can define the splits based on your ID column:

library(ComplexHeatmap)
ID=c(paste0("FD_", 1:3), paste0("FS_", 1:5), paste0("FE_", 1:4))
df <- data.frame(ID=ID,
                 matrix(rnorm(3*12, mean = 3), ncol=3, 
                        dimnames=list(ID, LETTERS[1:3])),
                 stringsAsFactors = FALSE)
splits <- factor(gsub("_.*", "", ID))
Heatmap(matrix=as.matrix(df[,-1] ), row_split = splits, cluster_row_slices = FALSE)

heatmap

0
votes

If you want list of dataframes based on ID, we can use split.

list_df <- split(df, sub("_.*", "", df$ID))
list_df

#$FD
#    ID   A   B   C
#1 FD_1 0.3 0.2 1.0
#2 FD_2 0.4 1.0 0.9
#3 FD_3 0.6 0.8 0.2

#$FE
#     ID   A   B   C
#9  FE_1 0.3 0.2 1.0
#10 FE_2 0.4 1.0 0.9
#11 FE_3 0.6 0.8 0.2
#12 FE_4 0.4 1.0 0.9

#$FS
#    ID   A   B   C
#4 FS_1 0.3 0.2 1.0
#5 FS_2 0.4 1.0 0.9
#6 FS_3 0.6 0.8 0.2
#7 FS_4 0.4 1.0 0.9
#8 FS_5 0.6 0.8 0.2
0
votes

We can use group_split

library(dplyr)
library(stringr)
list_df <- df %>%
              group_split(grp = str_remove(ID, "_.*"), keep = FALSE)