矩阵是元素布置成二维矩形布局的R对象。 它们包含相同原子类型的元素。
R创建矩阵的语法:
matrix(data, nrow, ncol, byrow, dimnames)
参数说明:
- data - 成为矩阵的数据元素输入向量。
- nrow - 是要创建的行数。
- ncol - 要被创建的列数。
- byrow - 是一个合乎逻辑。若为True,则输入向量元素按行安排。
- dimnames - 是分配给行和列名称。
Example
> # Elements are arranged sequentially by row. > M <- matrix(c(1:12), nrow=4, byrow=TRUE) > print(M) [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 9 [4,] 10 11 12 > # Elements are arranged sequentially by column. > N <- matrix(c(1:12), nrow=4, byrow=FALSE) > print(N) [,1] [,2] [,3] [1,] 1 5 9 [2,] 2 6 10 [3,] 3 7 11 [4,] 4 8 12 > # Define the column and row names. > rownames = c("row1", "row2", "row3", "row4") > colnames = c("col1", "col2", "col3") > P <- matrix(c(1:12), nrow=4, byrow=TRUE, dimnames=list(rownames, colnames)) > print(P) col1 col2 col3 row1 1 2 3 row2 4 5 6 row3 7 8 9 row4 10 11 12
访问矩阵:
> # Access the element at 3rd column and 1st row. > print(P[1,3]) [1] 3 > # Access the element at 2nd column and 4th row. > print(P[4,2]) [1] 11 > # Access only the 2nd row. > print(P[2,]) col1 col2 col3 4 5 6 > # Access only the 3rd column. > print(P[,3]) row1 row2 row3 row4 3 6 9 12
矩阵计算:
> # Create two 2x3 matrices. > matrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow=2) > print(matrix1) [,1] [,2] [,3] [1,] 3 -1 2 [2,] 9 4 6 > matrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow=2) > print(matrix2) [,1] [,2] [,3] [1,] 5 0 3 [2,] 2 9 4 > # Add the matrices. > result <- matrix1 + matrix2 > cat("Result of addition","n") Result of addition n > print(result) [,1] [,2] [,3] [1,] 8 -1 5 [2,] 11 13 10 > # Subtract the matrices > result <- matrix1 - matrix2 > cat("Result of subtraction","n") Result of subtraction n > print(result) [,1] [,2] [,3] [1,] -2 -1 -1 [2,] 7 -5 2 > # Multiply the matrices. > result <- matrix1 * matrix2 > cat("Result of multiplication","n") Result of multiplication n > print(result) [,1] [,2] [,3] [1,] 15 0 6 [2,] 18 36 24 > # Divide the matrices > result <- matrix1 / matrix2 > cat("Result of division","n") Result of division n > print(result) [,1] [,2] [,3] [1,] 0.6 -Inf 0.6666667 [2,] 4.5 0.4444444 1.5000000
参考网址:http://www.phperz.com/special/109.html