cliu
cliu

Reputation: 965

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:

$`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!

Upvotes: 0

Views: 43

Answers (1)

dcarlson
dcarlson

Reputation: 11066

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

Upvotes: 1

Related Questions