Elina Bochkova
Elina Bochkova

Reputation: 27

R: how to find the indices of the maximal value per column

Given this matrix

mat

     [,1] [,2] [,3]

[1,]    1    2    3

[2,]    7    8    1

[3,]    4    5    6

I want to find the maximum value in all columns plus their indices (row number). So basically, I need the following information:

max = [7 8 6]
ind = [2 2 3]

Thanks so much!

Upvotes: 0

Views: 430

Answers (2)

d.b
d.b

Reputation: 32558

transpose mat and use max.col

i = max.col(t(mat))
v = t(mat)[cbind(seq(NCOL(mat)), i)]
v
# [1] 7 8 6
i
# [1] 2 2 3

Upvotes: 1

akrun
akrun

Reputation: 887851

Use apply to loop over the columns (MARGIN = 2), get the max and the index of max (which.max) in a named vector as output

apply(mat, 2, function(x) c(max = max(x), ind = which.max(x)))

-output

     [,1] [,2] [,3]
max    7    8    6
ind    2    2    3

Or another option is colMaxs and max.col

library(matrixStats)
colMaxs(mat)
#[1] 7 8 6
max.col(t(mat))
#[1] 2 2 3

data

mat <- structure(c(1, 7, 4, 2, 8, 5, 3, 1, 6), .Dim = c(3L, 3L))

Upvotes: 2

Related Questions