`which()`用于矩阵索引的函数 [英] `which()` function for matrix indices
本文介绍了`which()`用于矩阵索引的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有一些矩阵,例如:
Say I have some matrix, for example:
> 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
如果我运行哪个
,我得到正常指数列表:
If I run which
, I get list of normal indices:
> which(m == 1)
[1] 3 6 9 12
我想要得到类似矩阵索引的东西 - 每个索引包含行号和列号:
I want to get something like matrix indices - each index containing the row and column number:
[,1] [,2]
[1,] 3 1
[2,] 2 2
[3,] 1 3
[4,] 4 3
是否有任何简单的函数可以执行此操作?此外,它应该以某种方式包含行和列名称:
Is there any simple function to do this? Moreover, it should somehow contain the row and column names:
> 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
但我现在不怎么样,或许像
but I don't now how, maybe like
[,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个向量(用于行和列),如
or, maybe return 2 vectors (for rows and columns), like
c b a d
3 2 1 4
e f g g
1 2 3 3
推荐答案
对于第一个问题,您还需要传递 arr.ind = T
到哪个
:
For your first question you need to also pass arr.ind=T
to which
:
> which(m == 1, arr.ind=T)
row col
[1,] 3 1
[2,] 2 2
[3,] 1 3
[4,] 4 3
这篇关于`which()`用于矩阵索引的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文