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

How to convert only row matrices in a list to column matrices in R?

I have a list of matrices where most of the matrices are column matrices but some of them are row matrices. How to convert only those row matrices to column matrices? I would like to achieve this using base R.

Here is the list of matrices where the third one is a row matrix

x <- list(`1` = matrix(1:20, nrow=5), `2` = matrix(1:20, nrow=10), `3` = matrix(1:5, nrow=1))

How to convert the list to one like this:

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

$`1`
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    3    5    7    9
[2,]    2    4    6    8   10

$`2`
     [,1] [,2]
[1,]    1    6
[2,]    2    7
[3,]    3    8
[4,]    4    9
[5,]    5   10

$`3`
[1,]    1    
[2,]    2    
[3,]    3   
[4,]    4    
[5,]    5  

I have a much larger dataset and so efficient code is preferred!

>Solution :

Check the dimensions of the matrix and transpose it if the row dimension is 1:

(y <- lapply(x, function(x) if(dim(x)[1] == 1) { t(x)} else x))
# $`1`
#      [,1] [,2] [,3] [,4]
# [1,]    1    6   11   16
# [2,]    2    7   12   17
# [3,]    3    8   13   18
# [4,]    4    9   14   19
# [5,]    5   10   15   20
# 
# $`2`
#       [,1] [,2]
#  [1,]    1   11
#  [2,]    2   12
#  [3,]    3   13
#  [4,]    4   14
#  [5,]    5   15
#  [6,]    6   16
#  [7,]    7   17
#  [8,]    8   18
#  [9,]    9   19
# [10,]   10   20
# 
# $`3`
#      [,1]
# [1,]    1
# [2,]    2
# [3,]    3
# [4,]    4
# [5,]    5
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