How can R language convert a list to a matrix?

In R language, you can convert a list to a matrix using the matrix() function. The syntax of the matrix() function is as follows:

matrix(data, nrow, ncol, byrow)

Explanation of parameters:

  1. Data that needs to be converted into a matrix can be in the form of a list, vector, or array.
  2. nrow: the number of rows in the matrix.
  3. Number of columns: the number of columns in the matrix.
  4. byrow: a logical value indicating whether to fill the matrix by row. The default is FALSE, indicating filling by column.

Here is an example demonstrating how to convert a list into a matrix.

# 创建一个列表
my_list <- list(1, 2, 3, 4, 5, 6)

# 将列表转换为矩阵
my_matrix <- matrix(my_list, nrow = 2, ncol = 3)

# 输出矩阵
print(my_matrix)

output result:

     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

In the example above, we created a list called my_list with 6 elements, and then used the matrix() function to convert this list into a matrix called my_matrix with 2 rows and 3 columns. Finally, we printed out the matrix.

bannerAds