w3resource

R Programming: Convert a Matrix to a List of Column-Vectors


Write a R program to convert a given matrix to a list of column-vectors.

Sample Solution:

R Programming Code:

# Create a 4x3 matrix with values from 1 to 12
x = matrix(1:12, ncol=3)

# Print the original matrix
print("Original matrix:")
print(x)

# Print a message indicating the following output is a list of column-vectors
print("list from the said matrix:")

# Convert the matrix to a list of column-vectors
l = split(x, rep(1:ncol(x), each = nrow(x)))

# Print the resulting list of column-vectors
print(l)

Output:

[1] "Original matrix:"
     [,1] [,2] [,3]
[1,]    1    5    9
[2,]    2    6   10
[3,]    3    7   11
[4,]    4    8   12
[1] "list from the said matrix:"
$`1`
[1] 1 2 3 4

$`2`
[1] 5 6 7 8

$`3`
[1]  9 10 11 12               

Explanation:

  • Create Matrix:
    • x = matrix(1:12, ncol=3):
      • Creates a matrix x with 12 elements, arranged into 3 columns. The elements are filled column-wise by default.
  • Print Original Matrix:
    • print("Original matrix:"):
      • Prints the message "Original matrix:".
    • print(x):
      • Displays the content of the matrix x.
  • Print Message for List Conversion:
    • print("list from the said matrix:"):
      • Prints the message "list from the said matrix:".
  • Convert Matrix to List of Column Vectors:
    • l = split(x, rep(1:ncol(x), each = nrow(x))):
      • Uses the split function to convert the matrix x into a list of column-vectors.
      • rep(1:ncol(x), each = nrow(x)) creates a vector that specifies how to split the matrix by columns, where 1:ncol(x) generates column indices, and each = nrow(x) repeats each index for the number of rows.
  • Print Resulting List:
    • print(l):
      • Displays the resulting list of column-vectors.

R Programming Code Editor:



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

Previous: Write a R program to create a correlation matrix from a dataframe of same data type.
Next: Write a R program to find row and column index of maximum and minimum value in a given matrix.

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.