R 如何使用行和列索引向量从数据帧或矩阵中提取特定值?
假设您有以下矩阵:R 如何使用行和列索引向量从数据帧或矩阵中提取特定值?,r,dataframe,matrix,R,Dataframe,Matrix,假设您有以下矩阵: mat <- matrix(1:12, nrow = 3, ncol = 4) print(mat) [,1] [,2] [,3] [,4] [1,] 1 4 7 10 [2,] 2 5 8 11 [3,] 3 6 9 12 我得到了一个新矩阵,其中包含了rowind和Colin的所有置换: [,1] [,2] [,3] [1,] 11 11 2 [2,] 12
mat <- matrix(1:12, nrow = 3, ncol = 4)
print(mat)
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
我得到了一个新矩阵,其中包含了rowind和Colin的所有置换:
[,1] [,2] [,3]
[1,] 11 11 2
[2,] 12 12 3
[3,] 10 10 1
如何取而代之地获得仅与特定行和列组合相关的值?我考虑过使用for循环,但鉴于我的矩阵和索引向量都很大,我觉得这样做速度太慢了,而且很可能有更好的方法。我们可以找到索引来提取值
mat[cbind(rowind, colind)]
#[1] 11 12 1
[,1] [,2] [,3]
[1,] 11 11 2
[2,] 12 12 3
[3,] 10 10 1
mat[cbind(rowind, colind)]
#[1] 11 12 1