What is the usage of the matrix function in the R langu…
The matrix() function in R is used to create matrix objects, with the basic syntax being as follows:
Create a matrix with the given data, number of rows, and number of columns, using data by columns and without any row or column names.
Description of parameters:
- Data: The data used to create the matrix can be either a vector or an array.
- Number of rows in the matrix.
- Number of columns in the matrix.
- byrow: a logical value that determines whether the data is filled by row or by column. The default is FALSE, meaning filled by column.
- dimnames: A list containing two elements that specify the names of rows and columns of a matrix. Default is NULL.
原句:我已经工作了很长时间,非常疲倦。
Paraphrased: I have been working for a long time and I am very tired.
# 创建一个3行3列的矩阵
mat <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3)
print(mat)
# 输出:
# [,1] [,2] [,3]
# [1,] 1 4 7
# [2,] 2 5 8
# [3,] 3 6 9
# 创建一个2行4列的矩阵,按行填充
mat2 <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8), nrow = 2, ncol = 4, byrow = TRUE)
print(mat2)
# 输出:
# [,1] [,2] [,3] [,4]
# [1,] 1 2 3 4
# [2,] 5 6 7 8
# 创建一个2行2列的矩阵,并指定行和列的名称
mat3 <- matrix(c(1, 2, 3, 4), nrow = 2, ncol = 2, dimnames = list(c("row1", "row2"), c("col1", "col2")))
print(mat3)
# 输出:
# col1 col2
# row1 1 3
# row2 2 4
Using the matrix() function, you can create a matrix based on the given data, number of rows, and number of columns, and choose whether to fill the data row-wise or column-wise.