Home Useful custom R functions
Post
Cancel

Useful custom R functions

Heatmaps

Given two matrices, this function plots heatmaps for each one with a fixed colour scale to allow for comparison.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
heatmap_scale = function(matrix1, matrix2, main1 = NULL, main2 = NULL, centr = FALSE){
  
  my_palette <- colorRampPalette(c("blue", "white", "red"))(n = 299)

  if(!centr){
    global_min <- min(matrix1, matrix2)
    global_max <- max(matrix1, matrix2)
  
    breaks = seq(global_min, global_max, length.out = 300)
  } else {
    breaks_ <- seq(-max(abs(global_min), abs(global_max)), 
                      max(abs(global_min), abs(global_max)), 
                      length.out = 300)
  }

  heatmap(matrix1, Colv = NA, Rowv = NA, scale = "none",
          col = my_palette, breaks = breaks, main = main1)
  heatmap(matrix2, Colv = NA, Rowv = NA, scale = "none",
          col = my_palette, breaks = breaks, main = main2)
  
}

Quick heatmap plot in R:

1
heatmap(matrix, Colv = NA, Rowv = NA,  scale = "none")

Eigen-analysis

Plot eigen values of covariance matrix

1
2
3
4
5
plot_eig_values = function(x, main = NULL){
     cov_d = (1/nrow(x)) * ( t(x) %*% x )
     cov_d_eig = eigen(cov_d)
     plot(cov_d_eig$values, main = main)
}

Max index of matrix

Get the row and column number of largest element of matrix

1
2
3
4
5
max_ind = function(mat){
  max_index <- which(mat == max(mat), arr.ind = TRUE)
  max_index
}

This post is licensed under CC BY 4.0 by the author.