Skip to content
Related Articles

Related Articles

Improve Article
Convert a given matrix to 1D array in R
  • Last Updated : 16 Mar, 2021

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

Functions Used

  • matrix() function in R is used to create a matrix

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 tha names assinged to rows and columns
  • vector() function is used to convert object into vector.

Syntax:

vector(object)



Approach

  • Create matrix
  • Pass the created matrix to vector function
  • Print array

Example 1:

R




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:

R




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



My Personal Notes arrow_drop_up
Recommended Articles
Page :