w3resource

R Programming - Convert a given Matrix to a List

R Programming: List Exercise-13 with Solution

Write a R program to convert a given matrix to a list.

Sample Solution :

R Programming Code :

# Create a matrix with values from 1 to 10, having 2 rows and 2 columns
m = matrix(1:10, nrow = 2, ncol = 2)

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

# Print the original matrix
print(m)

# Convert the matrix into a list by splitting it column-wise
l = split(m, rep(1:ncol(m), each = nrow(m)))

# Print the message indicating the list derived from the matrix
print("list from the said matrix:")

# Print the resulting list
print(l)

Output:

[1] "Original matrix:"
     [,1] [,2]
[1,]    1    3
[2,]    2    4
[1] "list from the said matrix:"
$`1`
[1] 1 2

$`2`
[1] 3 4                         

Explanation:

  • Create a Matrix:
    • m = matrix(1:10, nrow = 2, ncol = 2)
      • Creates a 2x2 matrix m with values from 1 to 10. The matrix will have 2 rows and 2 columns.
  • Print Original Matrix:
    • print("Original matrix:")
      • Prints the message "Original matrix:" to indicate the following output is the original matrix.
    • print(m)
      • Prints the matrix m.
  • Convert Matrix to List:
    • l = split(m, rep(1:ncol(m), each = nrow(m)))
      • Converts the matrix m into a list l.
      • The split function is used to split the matrix into a list of vectors, with each vector containing the elements of a column.
      • rep(1:ncol(m), each = nrow(m)) creates a repetition pattern to ensure that each column's elements are grouped together.
  • Print List from Matrix:
    • print("list from the said matrix:")
      • Prints the message "list from the said matrix:" to indicate the following output is the list derived from the matrix.
    • print(l)
      • Prints the list l, which contains the columns of the matrix as separate elements.

R Programming Code Editor:



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

Previous: Write a R program to convert a given dataframe to a list by rows.
Next: Write a R program to assign NULL to a given list element.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/r-programming-exercises/list/r-programming-list-exercise-13.php