|
row()与col()函数
在R中定义了的这两个函数用于取矩阵元素的行或列下标矩阵,例如矩阵A={aij}m×n,
row()函数将返回一个与矩阵A有相同维数的矩阵,该矩阵的第i行第j列元素为i,函数col()
类似。例如:
> x=matrix(1:12,3,4)
> row(x)
[,1] [,2] [,3] [,4]
[1,] 1 1 1 1
[2,] 2 2 2 2
[3,] 3 3 3 3
> col(x)
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 1 2 3 4
[3,] 1 2 3 4
这两个函数同样可以用于取一个矩阵的上下三角矩阵,例如:
> x
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
> x[row(x)<col(x)]=0
> x
[,1] [,2] [,3] [,4]
[1,] 1 0 0 0
[2,] 2 5 0 0
[3,] 3 6 9 0
> x=matrix(1:12,3,4)
> x[row(x)>col(x)]=0
> x
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 0 5 8 11
[3,] 0 0 9 12 |
|