Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Find index of Matrix with smallest value [duplicate]

Tags:

r

Given matrix

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

How do I find the column index/name and row index/name of the minimum value?

I've tried which.min, but I need to get the row/column index rather than the element. Any ideas?

like image 242
user1234440 Avatar asked Dec 05 '22 10:12

user1234440


1 Answers

You can use which

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

For example :

x <- matrix(c(1, 2, 0, 4), nrow = 2, ncol = 2)
which(x == min(x), arr.ind = TRUE)
##      row col
## [1,]   1   2
like image 173
dickoa Avatar answered Jan 05 '23 13:01

dickoa