2013-07-09 63 views
1

矩陣的指數由於矩陣R:查找與最小值

x <- matrix(c(1,2,3,4), nrow=2, ncol=2) 
colnames(x) <- c('a','b') 
rownames(x) <- c('c','d') 

如何找到最小值的列索引/名稱和行索引/叫什麼名字?

我試過which.min,但我需要得到行/列索引,而不是元素。有任何想法嗎?

+0

我想,你的意思是'colnames(X)< - C( 'A',」 b」, 'C', 'd')'? – nograpes

+1

哦,我無法在谷歌上找到這個問題,也許措辭......我們可以關閉它,如果你想 – user1234440

回答

5

您可以使用which

which(x == min(x), arr.ind = TRUE) 

例如:

x <- matrix(c(1, 2, 0, 4), nrow = 2, ncol = 2) 
which(x == min(x), arr.ind = TRUE) 
##  row col 
## [1,] 1 2 
+4

+1 - 'arrayInd(which.min(x),dim(x))'應該更快('x == min(x)'很貴)。它會一直返回第一個最小值,而你的所有值都會返回。 – flodel

1

如果你要像對待一個向量的矩陣可以使用which.min

which.min(x) 
# > [1] 1 
which.max(x) 
# > [1] 4 

作爲第一和第四元素。

您還可以找到最大和/位置返回有序向量w(而不是分鐘)

max.col(x) 
# [1] 2 2 
+0

好吧,然後執行'max.col(-x)'。但是,這給出了每行*的最小*位置,而不是OP的結果。 – flodel