verde
verde

Reputation: 25

how to point out a location with maxval in a vector

A question on pointing out a location with maximum value in a vector.

For say, i have a vector with 10 numbers,

x <- rnorm(10,0,1) [1]  1.1353978 -1.4852905 -0.1216639  0.1943784 -1.0968827  1.1051740  0.4738447 -0.6507678  0.2599902 -0.1355366


maxval <- max(x)
loc_val <- ? in this case, it should point out 1st element. loc_val <- 1

thanks.

Upvotes: 1

Views: 106

Answers (1)

Gavin Simpson
Gavin Simpson

Reputation: 174813

which.max() is your friend. See ?which.max and the example below:

R> set.seed(2)
R> x <- rnorm(10)
R> x
 [1] -0.89691455  0.18484918  1.58784533 -1.13037567 -0.08025176  0.13242028
 [7]  0.70795473 -0.23969802  1.98447394 -0.13878701
R> max(x)
[1] 1.984474
R> which.max(x)
[1] 9

Upvotes: 1

Related Questions