另一种访问R中矩阵元素的方法

KH *_*Kim 3 r matrix

mat <- matrix(c(1,2,3,4,5,6,7,8,9), ncol=3)

mat[1:2, 1:2] 
Run Code Online (Sandbox Code Playgroud)

返回新的matrix(c(1,2,4,5), ncol=2).

无论如何要访问矩阵元素,如情节的x,y位置?

一些function(mat, 1:2, 1:2)回报c(1,5)因为mat[1,1]并且mat[2,2]是1.5.

一些function(mat, c(1,1,2), c(2,1,1)回报

c(4, 1, 2)
Run Code Online (Sandbox Code Playgroud)

因为mat[1,2], mat[1,1], mat[2,1]是4,1,2.

Dav*_*son 6

您可以使用以下方式访问它cbind:

mat[cbind(1:2, 1:2)]
# [1] 1 5
mat[cbind(c(1, 1, 2), c(2, 1, 1))]
# [1] 4 1 2
Run Code Online (Sandbox Code Playgroud)