How can R language convert a vector into a matrix?
In R language, you can use the matrix() function to convert a vector into a matrix. The basic syntax of this function is as follows:
matrix(data, nrow, ncol, byrow)
Here, data represents the vector to be converted into a matrix, nrow indicates the number of rows in the matrix, ncol indicates the number of columns in the matrix, and byrow specifies whether to fill the matrix by rows. If byrow is FALSE (the default value), the matrix is filled by columns; if byrow is TRUE, the matrix is filled by rows.
Here is an example showing how to convert a vector into a matrix.
# 创建一个向量
vec <- c(1, 2, 3, 4, 5, 6)
# 将向量转化为2行3列的矩阵按列填充
mat <- matrix(vec, nrow = 2, ncol = 3, byrow = FALSE)
# 打印矩阵
print(mat)
The output result is:
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
In the example above, the vector vec is transformed into a 2 by 3 matrix and filled by columns.