Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Subset a list of matrices by common column names

I want to subset a list of matrices based on common/shared column names. My current code returns an empty mat.list.

mat.list <- list(mRNA=as.matrix(mrna.deg), Methylation=as.matrix(diff.meth), Protein=as.matrix(protein.dep))
col <- Reduce(intersect, lapply(mat.list, colnames))
mat.list <- lapply(mat.list, function(x) x[col])

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Unlike data frames, which you can subset with df['colname'], when subsetting a matrix or array in R, you need to specify the margin along which you are subsetting. In other words you need to do x[, col] instead of x[col] in your last lapply. Here’s a reprex to demonstrate:

mat1 <- matrix(1:9, 3, dimnames = list(1:3, c('A', 'B', 'C')))
mat2 <- matrix(1:9, 3, dimnames = list(1:3, c('C', 'D', 'E')))

mat.list <- list(mRNA = mat1, Methylation = mat2, Protein = mat1)
col <- Reduce(intersect, lapply(mat.list, colnames))
mat.list <- lapply(mat.list, function(x) x[, col])

mat.list
#> $mRNA
#> 1 2 3 
#> 7 8 9 
#> 
#> $Methylation
#> 1 2 3 
#> 1 2 3 
#> 
#> $Protein
#> 1 2 3 
#> 7 8 9

Created on 2023-05-25 with reprex v2.0.2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading