R矩阵

示例

对于对象的每个维度,[运算符采用一个参数。向量具有一维并采用一个参数。矩阵和数据帧具有两个维度,并采取两个参数,给定为[i, j]其中i是的行和j是列。索引从1开始。

## a sample matrix
mat <- matrix(1:6, nrow = 2, dimnames = list(c("row1", "row2"), c("col1", "col2", "col3")))

mat
#      col1 col2 col3
# row1    1    3    5
# row2    2    4    6

mat[i,j]是矩阵的i第th行j第th列中的元素mat。例如,的i值2和的j值1给出矩阵第二行和第一列中的数字。忽略i或j返回该维度中的所有值。

mat[ , 3]
## row1 row2 
##    5    6 

mat[1, ]
# col1 col2 col3 
#    1    3    5

当矩阵具有行名或列名(不是必需的)时,这些可用于子集:

mat[ , 'col1']
# row1 row2 
#    1    2

默认情况下,子集的结果将尽可能简化。如果子集只有一维,如上面的示例,结果将是一维向量,而不是二维矩阵。可以使用以下drop = FALSE参数覆盖此默认值[:

## This selects the first row as a vector
class(mat[1, ])
# [1] "integer"

## Whereas this selects the first row as a 1x3 matrix:
class(mat[1, , drop = F])
# [1] "matrix"

当然,如果选择本身具有两个尺寸,则不能删除尺寸:

mat[1:2, 2:3]  ## A 2x2 matrix
#      col2 col3
# row1    3    5
# row2    4    6


通过其位置选择各个矩阵条目

也可以使用Nx2矩阵从矩阵中选择N个单独的元素(例如坐标系统的工作方式)。如果要在向量中提取矩阵中的项,(1st row, 1st column), (1st row, 3rd column), (2nd row, 3rd column), (2nd row, 1st column)可以轻松创建一个具有这些坐标的索引矩阵,然后使用该子集对矩阵进行子集化:

mat
#      col1 col2 col3
# row1    1    3    5
# row2    2    4    6

ind = rbind(c(1, 1), c(1, 3), c(2, 3), c(2, 1))
ind
#      [,1] [,2]
# [1,]    1    1
# [2,]    1    3
# [3,]    2    3
# [4,]    2    1

mat[ind]
# [1] 1 5 6 2

在上面的示例中,ind矩阵的第一列引用中的行mat,的第二列ind引用中的列mat。