在R語(yǔ)言中,matrix()函數(shù)用于創(chuàng)建矩陣對(duì)象。它的基本用法如下:
matrix(data, nrow, ncol, byrow = FALSE, dimnames = NULL)
參數(shù)說(shuō)明:
示例:
# 創(chuàng)建一個(gè)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
# 創(chuàng)建一個(gè)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
# 創(chuàng)建一個(gè)2行2列的矩陣,并指定行和列的名稱(chēng)
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
通過(guò)matrix()函數(shù),你可以根據(jù)給定的數(shù)據(jù)、行數(shù)和列數(shù)創(chuàng)建一個(gè)矩陣,并可以選擇按行或按列填充數(shù)據(jù)。