R `哪个函数用于矩阵索引
假设我有一些矩阵,例如:R `哪个函数用于矩阵索引,r,matrix,indexing,R,Matrix,Indexing,假设我有一些矩阵,例如: > m = matrix(rep(c(0, 0, 1), 4), nrow = 4) > m [,1] [,2] [,3] [1,] 0 0 1 [2,] 0 1 0 [3,] 1 0 0 [4,] 0 0 1 如果我运行哪个,我会得到正常索引列表: > which(m == 1) [1] 3 6 9 12 我想得到类似矩阵索引的东西-每个索引都包含行和列编号:
> m = matrix(rep(c(0, 0, 1), 4), nrow = 4)
> m
[,1] [,2] [,3]
[1,] 0 0 1
[2,] 0 1 0
[3,] 1 0 0
[4,] 0 0 1
如果我运行哪个
,我会得到正常索引列表:
> which(m == 1)
[1] 3 6 9 12
我想得到类似矩阵索引的东西-每个索引都包含行和列编号:
[,1] [,2]
[1,] 3 1
[2,] 2 2
[3,] 1 3
[4,] 4 3
有什么简单的函数可以实现这一点吗?此外,它应该以某种方式包含行名和列名:
> rownames(m) = letters[1:4]
> colnames(m) = letters[5:7]
> m
e f g
a 0 0 1
b 0 1 0
c 1 0 0
d 0 0 1
但我现在不知道如何,也许像
[,1] [,2] [,3] [,4]
[1,] 3 1 c e
[2,] 2 2 b f
[3,] 1 3 a g
[4,] 4 3 d g
或者,可能返回2个向量(行和列),如
对于第一个问题,您还需要将
arr.ind=TRUE
传递给哪个
:
> which(m == 1, arr.ind = TRUE)
row col
[1,] 3 1
[2,] 2 2
[3,] 1 3
[4,] 4 3
不能在矩阵中混合数字和字母,但可以在data.frame中:
> indices <- data.frame(ind= which(m == 1, arr.ind=TRUE))
> indices$rnm <- rownames(m)[indices$ind.row]
> indices$cnm <- colnames(m)[indices$ind.col]
> indices
ind.row ind.col rnm cnm
c 3 1 c e
b 2 2 b f
a 1 3 a g
d 4 3 d g
>索引$rnm索引$cnm索引
ind.row ind.col rnm cnm
C31CE
B2BF
a 13 a g
d 4 3 d g
很酷,谢谢!我正在查看?它的帮助,但是它说:“arr.ind logical-当x是数组时是否应该返回数组索引?”,这让人非常困惑!为什么他们在返回矩阵索引时会提到数组索引?(对于数组,我通常是指1D向量)“数组”是更一般的情况,包括具有退化单态维数的“向量”、矩阵(具有2维)和3D、4D、。。。数组-在这个意义上,没有维度的向量不是1D,记住还有递归向量(list)@TomasT。数组可以有1、2或更多维度。矩阵是二维数组的特例。参见?矩阵
和?数组
。我真不敢相信我从来都不知道arr.ind
!我总是使用一些可怕的低效黑客,依靠调用row()
和col()
来实现这一点。请参阅
> indices <- data.frame(ind= which(m == 1, arr.ind=TRUE))
> indices$rnm <- rownames(m)[indices$ind.row]
> indices$cnm <- colnames(m)[indices$ind.col]
> indices
ind.row ind.col rnm cnm
c 3 1 c e
b 2 2 b f
a 1 3 a g
d 4 3 d g