ghb
ghb

Reputation:

Choosing highest number in vector and knowing its position in R

I have a vector in R:

y=c(-29.900900, 5.728916, 35.234331,  11.854811,  61.309519,  50.432798, -27.654741,  21.413622, -10.805339, -37.504199)

I would like to select the highest number using for example max(y).

Then it gives me 61.309519.

BUT in addition I would like to know the position i.e. that its the 5th element in the vector.

Is there any way to do this? I'm ok with using other data formats eg. matrix or data.frame

Upvotes: 2

Views: 1934

Answers (2)

Carl Witthoft
Carl Witthoft

Reputation: 21502

Since you mentioned using matrices,
which(mymatrix == max(mymatrix), arr.ind=TRUE) will locate the element by row and column.

Upvotes: 2

bartektartanus
bartektartanus

Reputation: 16080

which.max() 

function will return the index of first maximum element. This might be important when you have more than one maximum in vector.

Upvotes: 9

Related Questions