R 矩陣
矩陣
矩陣是二維資料集,包含列和行。
列是資料的垂直表示,而行是資料的水平表示。
可以使用 matrix()
函式建立矩陣。指定 nrow
和 ncol
引數來設定行數和列數。
注意: 記住 c()
函式用於連線項。
您也可以使用字串建立矩陣。
示例
thismatrix <- matrix(c("apple", "banana", "cherry", "orange"), nrow = 2, ncol = 2)
thismatrix
自己動手試一試 »
訪問矩陣項
您可以使用 [ ]
方括號訪問項。方括號中的第一個數字“1”指定行位置,第二個數字“2”指定列位置。
示例
thismatrix <- matrix(c("apple", "banana", "cherry", "orange"), nrow = 2, ncol = 2)
thismatrix[1, 2]
自己動手試一試 »
如果您在括號中的數字後面指定逗號,則可以訪問整行。
示例
thismatrix <- matrix(c("apple", "banana", "cherry", "orange"), nrow = 2, ncol = 2)
thismatrix[2,]
自己動手試一試 »
如果您在括號中的數字前面指定逗號,則可以訪問整列。
示例
thismatrix <- matrix(c("apple", "banana", "cherry", "orange"), nrow = 2, ncol = 2)
thismatrix[,2]
自己動手試一試 »
訪問多行
如果使用 c()
函式,則可以訪問多行。
示例
thismatrix <- matrix(c("apple", "banana", "cherry", "orange","grape", "pineapple", "pear", "melon", "fig"), nrow = 3, ncol = 3)
thismatrix[c(1,2),]
自己動手試一試 »
訪問多列
如果使用 c()
函式,則可以訪問多列。
示例
thismatrix <- matrix(c("apple", "banana", "cherry", "orange","grape", "pineapple", "pear", "melon", "fig"), nrow = 3, ncol = 3)
thismatrix[, c(1,2)]
自己動手試一試 »
新增行和列
使用 cbind()
函式在矩陣中新增其他列。
示例
thismatrix <- matrix(c("apple", "banana", "cherry", "orange","grape", "pineapple", "pear", "melon", "fig"), nrow = 3, ncol = 3)
newmatrix <- cbind(thismatrix, c("strawberry", "blueberry", "raspberry"))
# 列印新矩陣
newmatrix
自己動手試一試 »
注意: 新列中的單元格必須與現有矩陣的長度相同。
使用 rbind()
函式在矩陣中新增其他行。
示例
thismatrix <- matrix(c("apple", "banana", "cherry", "orange","grape", "pineapple", "pear", "melon", "fig"), nrow = 3, ncol = 3)
newmatrix <- rbind(thismatrix, c("strawberry", "blueberry", "raspberry"))
# 列印新矩陣
newmatrix
自己動手試一試 »
注意: 新行中的單元格必須與現有矩陣的長度相同。
刪除行和列
使用 c()
函式刪除矩陣中的行和列。
示例
thismatrix <- matrix(c("apple", "banana", "cherry", "orange", "mango", "pineapple"), nrow = 3, ncol =2)
# 刪除第一行和第一列
thismatrix <- thismatrix[-c(1), -c(1)]
thismatrix
自己動手試一試 »
檢查項是否存在
要查詢指定的項是否在矩陣中,請使用 %in%
運算子。
示例
檢查矩陣中是否存在“apple”
thismatrix <- matrix(c("apple", "banana", "cherry", "orange"), nrow = 2, ncol = 2)
"apple" %in% thismatrix
自己動手試一試 »
行數和列數
使用 dim()
函式查詢矩陣中的行數和列數。
示例
thismatrix <- matrix(c("apple", "banana", "cherry", "orange"), nrow = 2, ncol = 2)
dim(thismatrix)
自己動手試一試 »
矩陣長度
使用 length()
函式查詢矩陣的維度。
示例
thismatrix <- matrix(c("apple", "banana", "cherry", "orange"), nrow = 2, ncol = 2)
length(thismatrix)
自己動手試一試 »
矩陣中的總單元格數是行數乘以列數。
在上面的示例中:維度 = 2*2 = **4**。
遍歷矩陣
您可以使用 for
迴圈遍歷矩陣。迴圈將從第一行開始,向右移動。
示例
迴圈遍歷矩陣項並列印它們
thismatrix <- matrix(c("apple", "banana", "cherry", "orange"), nrow = 2, ncol = 2)
for (rows in 1:nrow(thismatrix)) {
for (columns in 1:ncol(thismatrix)) {
print(thismatrix[rows, columns])
}
}
自己動手試一試 »
合併兩個矩陣
同樣,您可以使用 rbind()
或 cbind()
函式將兩個或多個矩陣合併在一起。
示例
# 合併矩陣
Matrix1 <- matrix(c("apple", "banana", "cherry", "grape"), nrow = 2, ncol = 2)
Matrix2 <- matrix(c("orange", "mango", "pineapple", "watermelon"), nrow = 2, ncol = 2)
# 按行新增
Matrix_Combined <- rbind(Matrix1, Matrix2)
Matrix_Combined
# 按列新增
Matrix_Combined <- cbind(Matrix1, Matrix2)
Matrix_Combined
自己動手試一試 »