How to convert an array into a matrix in R?


To convert an array into a matrix in R, we can use apply function. For example, if we have an array called ARRAY that contains 2 array elements then we can convert this array into a single matrix using the command apply(ARRAY,2,c). We need to understand the dimension of the array making the conversion otherwise the output will not be as expected.

Example

Consider the below array −

 Live Demo

x1<-array(1:50,dim=c(5,5,2))
x1
, , 1

Output

    [,1] [,2] [,3] [,4]  [,5]
[1,]  1   6    11   16    21
[2,]  2   7    12   17    22
[3,]  3   8    13   18    23
[4,]  4   9    14   19    24
[5,]  5  10    15   20    25
, , 2
    [,1] [,2] [,3] [,4] [,5]
[1,] 26  31   36   41   46
[2,] 27  32   37   42   47
[3,] 28  33   38   43   48
[4,] 29  34   39   44   49
[5,] 30  35   40   45   50

Converting x1 into a matrix −

Example

apply(x1,2,c)

Output

    [,1] [,2] [,3] [,4] [,5]
[1,]  1    6   11   16   21
[2,]  2    7   12   17   22
[3,]  3    8   13   18   23
[4,]  4    9   14   19   24
[5,]  5   10   15   20   25
[6,] 26   31   36   41   46
[7,] 27   32   37   42   47
[8,] 28   33   38   43   48
[9,] 29   34   39   44   49
[10,] 30  35   40   45   50

Example

 Live Demo

x2<-array(rpois(20,5),dim=c(10,2,2))
x2

Output

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

Converting x2 into a matrix −

Example

apply(x2,2,c)

Output

   [,1] [,2]
[1,] 8    7
[2,] 8    9
[3,] 6    6
[4,] 5    5
[5,] 5    6
[6,] 5    7
[7,] 1    3
[8,] 8    7
[9,] 6    3
[10,] 3   2
[11,] 8   7
[12,] 8   9
[13,] 6   6
[14,] 5   5
[15,] 5   6
[16,] 5   7
[17,] 1   3
[18,] 8   7 
[19,] 6   3
[20,] 3   2

Updated on: 17-Mar-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements