# Is there a better way to get the index of a minimum?

Consider the following reproducible example:

# note that lh is a standard ts dataset that ships with R
lh
# fit an R model
ar.mle<-ar(lh,method="mle")

# now get the min AIC, this is the relevant line:
ar.mle$aic[ar.mle$aic==min(ar.mle$aic)] This works fine and gives back the smallest AIC value and it's index, which is the suggested AR order. I feel I am repeating myself in this last line of code. Is there an easier way to obtain index and value? I know I could use partial autocorrelations to determine the level, too. This is not a stats question, but an R indexing question. ## migrated from stackoverflow.comAug 14 '11 at 14:01 This question came from our site for professional and enthusiast programmers. • Try which([blahblah], arr.ind=TRUE) – Carl Witthoft Aug 13 '11 at 14:14 ## 2 Answers perhaps the function which.min() would do the trick? which.min(ar.mle$aic)

it won't shorten your code all that much:

ar.mle$aic[which.min(ar.mle$aic)]
• nice start tim :) – ran2 Aug 14 '11 at 7:38

Well, it really doesn't return an index and value, what you get is a named value.

> ans <- ar.mle$aic[which.min(ar.mle$aic)]
> names(ans)
[1] "3"

The index itself is actually 4 (and is an integer); R indexes from 1.

> which.min(ar.mle$aic) 3 4 > which.min(ar.mle$aic) == 4
3
TRUE

(yes, this idea of tagging names to values is rather weird, coming from any other language)