使用 `which()` 获取匹配项的行和列索引 [英] Get row and column indices of matches using `which()`

查看:36
本文介绍了使用 `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

如果我运行 which,我会得到正常索引的列表:

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= TRUE 传递给 which:>

For your first question you need to also pass arr.ind= TRUE to which:

> which(m == 1, arr.ind = TRUE)
     row col
[1,]   3   1
[2,]   2   2
[3,]   1   3
[4,]   4   3

这篇关于使用 `which()` 获取匹配项的行和列索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆