|
创建一个矩阵
在R中可以用函数matrix()来创建一个矩阵,应用该函数时需要输入必要的参数值。
> args(matrix)
function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames
= NULL)
data 项为必要的矩阵元素,nrow 为行数,ncol 为列数,注意nrow 与ncol 的乘积应为
矩阵元素个数,byrow 项控制排列元素时是否按行进行,dimnames 给定行和列的名称。
例如:
> matrix(1:12,nrow=3,ncol=4)
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
> matrix(1:12,nrow=4,ncol=3)
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
> matrix(1:12,nrow=4,ncol=3,byrow=T)
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
[4,] 10 11 12
> rowname
[1] "r1" "r2" "r3"
> colname=c("c1","c2","c3","c4")
> colname
[1] "c1" "c2" "c3" "c4"
> matrix(1:12,nrow=3,ncol=4,dimnames=list(rowname,colname))
c1 c2 c3 c4
r1 1 4 7 10
r2 2 5 8 11 |
|