w3resource

R Programming: Convert a Matrix to a 1 Dimensional Array


Write a R program to convert a given matrix to a 1 dimensional array.

Sample Solution :

R Programming Code :

 # Create a matrix 'm' with 3 rows and 4 columns filled with values from 1 to 12
m = matrix(1:12, 3, 4)

# Print a message indicating the original matrix
print("Original matrix:")

# Display the original matrix
print(m)

# Convert the matrix 'm' to a 1-dimensional array
a = as.vector(m)

# Print a message indicating the 1-dimensional array
print("1 dimensional array:")

# Display the 1-dimensional array
print(a)

Output:

[1] "Original matrix:"
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
[1] "1 dimensional array:"
 [1]  1  2  3  4  5  6  7  8  9 10 11 12                         

Explanation:

  • m=matrix(1:12,3,4): Creates a matrix m with 3 rows and 4 columns, filled with values from 1 to 12.
  • print("Original matrix:"): Prints a message indicating the start of the matrix display.
  • print(m): Displays the original matrix m.
  • a = as.vector(m): Converts the matrix m into a 1-dimensional array a.
  • print("1 dimensional array:"): Prints a message indicating the start of the array display.
  • print(a): Displays the 1-dimensional array a obtained from the matrix.

Go to:


PREV : R Programming Array Exercises Home.
NEXT : Write a R program to create an array of two 3x3 matrices each with 3 rows and 3 columns from two given two vectors.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.