How to input a custom matrix in R language?
In R programming language, you can use the matrix() function to create custom matrices. The basic syntax of the matrix() function is as follows:
matrix(data, nrow, ncol, byrow, dimnames)
The meanings of the parameters are as follows:
- Data: The data of the matrix can be a vector or a matrix.
- nrow: the number of rows in the matrix.
- Number of columns in the matrix.
- byrow: a logical value indicating whether the data is filled into the matrix by row or by column, with a default value of FALSE (filled by column).
- Dimnames: a list of length 2 containing row names and column names.
Here are a few examples:
# 创建一个3行2列的矩阵
mat1 <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 3, ncol = 2)
print(mat1)
# 创建一个2行3列的矩阵,按行填充
mat2 <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3, byrow = TRUE)
print(mat2)
# 创建一个有行名和列名的矩阵
mat3 <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3, dimnames = list(c("A", "B"), c("X", "Y", "Z")))
print(mat3)
The code above will output:
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
X Y Z
A 1 4 5
B 2 3 6
I hope this helps you!