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 :

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

Leave a Reply