R中矩阵的索引值? [英] Index value for matrix in R?

查看:112
本文介绍了R中矩阵的索引值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有获取矩阵索引(行号和列号)的函数?

Is there a function to get an index (row number and column number) for a matrix?

假设我有一个简单的矩阵:

Suppose that I have a simple matrix:

a <- matrix(1:50, nrow=5)

例如,是否有一种简单的方法来为数字"23"取回c(3,5)之类的东西?在这种情况下,说which(a==23)只会返回23.

Is there an easy way to get back something like c(3, 5) for the number "23", for instance? In this case, saying which(a==23) just returns 23.

这似乎可行,但是我敢肯定有更好的方法:

This seems to work but I'm sure that there's a better way:

matrix.index <- function(a, value) {
  idx <- which(data.frame(a)==value)
  col.num <- ceiling(idx/nrow(a))
  row.num <- idx - (col.num-1) * nrow(a)
  return(c(row.num, col.num))
}
> matrix.index(a, 23)
[1] 3 5
> matrix.index(a, 50)
[1]  5 10

推荐答案

在发布此内容后,仅查看了which()的帮助,并找到了答案:arr.ind参数.

Just looked at the help for which() after posting this and found the answer: the arr.ind parameter.

which(a==23, arr.ind=TRUE)
     row col
[1,]   3   5

这篇关于R中矩阵的索引值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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