R获得矩阵中每一行的最小值,并返回行名和列名 [英] R getting the minimum value for each row in a matrix, and returning the row and column name

查看:1700
本文介绍了R获得矩阵中每一行的最小值,并返回行名和列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的矩阵:

I have a matrix like so:

实际上只有数百或数千个值.

Only in reality it is hundreds or thousands of values.

我需要做的是返回每一行的最小值,以及行/列的名称.

What I need to do is return the minimum value for each row, along with the row/col name.

因此,对于示例"BAC"中的第1行,BAC/CSCO的最小值为0.92,因此我需要返回以下内容:

So for row 1 in the example, "BAC", the minimum is 0.92 for BAC/CSCO, so I need to return something like:

BAC/CSCO 0.92

BAC/CSCO 0.92

然后对矩阵中的每一行重复一次.

And then repeat this for each row in the matrix.

我们非常感谢您的协助.我认为套用是技巧,但是我不能完全找到正确的组合.

Assistance is greatly appreciated. I think apply is the trick, but I can't quite get the right combination.

推荐答案

X <- matrix(runif(20), nrow=4)
rownames(X) <- paste0("foo", seq(nrow(X)))
colnames(X) <- paste0("bar", seq(ncol(X)))

result <- t(sapply(seq(nrow(X)), function(i) {
  j <- which.min(X[i,])
  c(paste(rownames(X)[i], colnames(X)[j], sep='/'), X[i,j])
}))

print(X)
print(result)

会给您:

          bar1      bar2       bar3       bar4      bar5
foo1 0.2085419 0.6290522 0.12730378 0.17775105 0.3239684
foo2 0.8061464 0.7948392 0.09330563 0.06698921 0.5557932
foo3 0.1790950 0.7788139 0.35787944 0.39117325 0.2578457
foo4 0.9099254 0.4048508 0.54791272 0.38674301 0.3272156

     [,1]        [,2]                
[1,] "foo1/bar3" "0.127303782384843" 
[2,] "foo2/bar4" "0.0669892099685967"
[3,] "foo3/bar1" "0.179094966035336" 
[4,] "foo4/bar5" "0.327215566998348" 

这篇关于R获得矩阵中每一行的最小值,并返回行名和列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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