Open In App

Convert a given matrix to 1D array in R

In this article, let’s discuss how to convert a Matrix to a 1D array in R. 

Functions Used

Syntax: matrix(data,nrow,ncol,byrow,dimnames)



Parameter:

  • data-is the input vector which becomes the data elements of the matrix
  • nrow-is the numbers of rows to be created
  • ncol-is the numbers of columns to be created
  • byrow-is a logical clue,if it is true then input vector elements are arranged by row
  • dimname-is the names assigned to rows and columns

Syntax:



vector(object)

Approach

Example 1:




rows=c("r1","r2")
cols=c("c1","c2","c3","c4")
 
M=matrix(c(2:9),nrow=2,byrow=TRUE,dimnames=list(rows,cols))
 
print("Original matrix:")
print(M)
 
output=as.vector(M)
 
print("1D array :")
print(output)

Output 

[1] "Original matrix:"
  c1 c2 c3 c4
r1  2  3  4  5
r2  6  7  8  9
[1] "1D array :"
[1] 2 6 3 7 4 8 5 9

We can also convert only a given number of rows, for that simply pass the required number as value to nrow.

Example: 




rows=c("r1","r2","r3","r4")
cols=c("c1","c2","c3","c4")
 
M=matrix(c(2:17),nrow=4,byrow=TRUE,dimnames=list(rows,cols))
 
print("Original matrix:")
print(M)
 
output=as.vector(M)
 
print("1D array :")
print(output)

Output: 

[1] "Original matrix:"
  c1 c2 c3 c4
r1  2  3  4  5
r2  6  7  8  9
r3 10 11 12 13
r4 14 15 16 17
[1] "1D array :"
[1]  2  6 10 14  3  7 11 15  4  8 12 16  5  9 13 17

 


Article Tags :