
- R 教程
- R - 首頁
- R - 概述
- R - 環境設定
- R - 基本語法
- R - 資料型別
- R - 變數
- R - 運算子
- R - 決策
- R - 迴圈
- R - 函式
- R - 字串
- R - 向量
- R - 列表
- R - 矩陣
- R - 陣列
- R - 因子
- R - 資料框
- R - 包
- R - 資料重塑
R - 矩陣
矩陣是R物件,其元素以二維矩形佈局排列。它們包含相同原子型別的元素。雖然我們可以建立一個只包含字元或邏輯值的矩陣,但它們並沒有多大用處。我們使用包含數值元素的矩陣進行數學計算。
可以使用matrix()函式建立矩陣。
語法
在R中建立矩陣的基本語法為:
matrix(data, nrow, ncol, byrow, dimnames)
以下是所用引數的說明:
data 是輸入向量,它成為矩陣的資料元素。
nrow 是要建立的行數。
ncol 是要建立的列數。
byrow 是一個邏輯線索。如果為 TRUE,則按行排列輸入向量元素。
dimname 是分配給行和列的名稱。
示例
建立一個以數字向量作為輸入的矩陣。
# Elements are arranged sequentially by row. M <- matrix(c(3:14), nrow = 4, byrow = TRUE) print(M) # Elements are arranged sequentially by column. N <- matrix(c(3:14), nrow = 4, byrow = FALSE) print(N) # Define the column and row names. rownames = c("row1", "row2", "row3", "row4") colnames = c("col1", "col2", "col3") P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames, colnames)) print(P)
執行上述程式碼後,將產生以下結果:
[,1] [,2] [,3] [1,] 3 4 5 [2,] 6 7 8 [3,] 9 10 11 [4,] 12 13 14 [,1] [,2] [,3] [1,] 3 7 11 [2,] 4 8 12 [3,] 5 9 13 [4,] 6 10 14 col1 col2 col3 row1 3 4 5 row2 6 7 8 row3 9 10 11 row4 12 13 14
訪問矩陣元素
可以使用元素的列和行索引訪問矩陣的元素。我們考慮上面的矩陣P來查詢下面的特定元素。
# Define the column and row names. rownames = c("row1", "row2", "row3", "row4") colnames = c("col1", "col2", "col3") # Create the matrix. P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames, colnames)) # Access the element at 3rd column and 1st row. print(P[1,3]) # Access the element at 2nd column and 4th row. print(P[4,2]) # Access only the 2nd row. print(P[2,]) # Access only the 3rd column. print(P[,3])
執行上述程式碼後,將產生以下結果:
[1] 5 [1] 13 col1 col2 col3 6 7 8 row1 row2 row3 row4 5 8 11 14
矩陣計算
使用R運算子對矩陣執行各種數學運算。運算的結果也是一個矩陣。
參與運算的矩陣的維數(行數和列數)應相同。
矩陣加法和減法
# Create two 2x3 matrices. matrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow = 2) print(matrix1) matrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow = 2) print(matrix2) # Add the matrices. result <- matrix1 + matrix2 cat("Result of addition","\n") print(result) # Subtract the matrices result <- matrix1 - matrix2 cat("Result of subtraction","\n") print(result)
執行上述程式碼後,將產生以下結果:
[,1] [,2] [,3] [1,] 3 -1 2 [2,] 9 4 6 [,1] [,2] [,3] [1,] 5 0 3 [2,] 2 9 4 Result of addition [,1] [,2] [,3] [1,] 8 -1 5 [2,] 11 13 10 Result of subtraction [,1] [,2] [,3] [1,] -2 -1 -1 [2,] 7 -5 2
矩陣乘法和除法
# Create two 2x3 matrices. matrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow = 2) print(matrix1) matrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow = 2) print(matrix2) # Multiply the matrices. result <- matrix1 * matrix2 cat("Result of multiplication","\n") print(result) # Divide the matrices result <- matrix1 / matrix2 cat("Result of division","\n") print(result)
執行上述程式碼後,將產生以下結果:
[,1] [,2] [,3] [1,] 3 -1 2 [2,] 9 4 6 [,1] [,2] [,3] [1,] 5 0 3 [2,] 2 9 4 Result of multiplication [,1] [,2] [,3] [1,] 15 0 6 [2,] 18 36 24 Result of division [,1] [,2] [,3] [1,] 0.6 -Inf 0.6666667 [2,] 4.5 0.4444444 1.5000000
廣告