thx for your help!
I have 2 matrices: Mx1 and Mx2 And I would like to make heatmaps using pheatmap by looping on selected matrices in the R environment
I tried:
Matrices_list <- c(Mx1, Mx2)
for( i in Matrices_list_list ){pheatmap(i, filename= "i.pdf")}
but obviously doesn't works The problems is that the Df_list now is a merge of both Mx instead of 2 distinct datasets in which I cant loop. Its looping in each element of the combined Df_list
Desired output:
pheatmap(Mx1, filename="Mx1.pdf")
pheatmap(Mx2, filename="Mx2.pdf")
Thx again for your help :)
A matrix
is a vector
with dim
ension attributes (usually 2D). The use of c
function on two matrices, removes the dimension attributes and return a single 1 dimensional vector with length
equal to the length(Mx1)
+ length(Mx2)
.
As showed in the comments, if we need to keep the matrix
as itself store it in a list
with names
attribute as the object names of the individual matrices. With dplyr::lst
, by default it generates the names
of the list
as object names
library(dplyr)
Matrices_list <- lst(Mx1, Mx2)
Regarding the for
loop used in OP's post
for(i in Matrices_list ){...
the i
is the individual matrix element, which doesn't have any names attribute. This can be otherwise described as a for
each loop i.e. for each element 'x' of 'Matrices_list'. In other languages such as C++
, the for each syntax would be
for(auto i : Matrices_list) {...
Instead of looping over the object elements, loop over the sequence
for(i in seq_along(Matrices_list)) {...
or the names
attribute, extract those elements and the corresponding names to construct the file name.
With tidyverse, we can use imap
or iwalk
with .x
the matrix element and .y
the names of the list
or the index (if the names are absent)
library(purrr)
library(stringr)
imap(Matrices_list, ~ pheatmap(.x, filename = str_c(.y, ".pdf")))
iwalk(Matrices_list, ~ pheatmap(.x, filename = str_c(.y, ".pdf")))
The difference in imap/iwalk
is that iwalk
doesn't print the return value on the console.