Leah Bevis
Leah Bevis

Reputation: 386

How to write a function like which.min but for bottom 3 values?

I want to write a function that gives the 3 indices of the bottom 3 values of a vector -- just like which.min, but the bottom 3 indices instead of the bottom index.

I wrote a function (minfunc, below) that can be called by apply() to find the bottom 3 values of a vector. But right now I have no function to find the indices of those 3 minimum values.

minfunc <- function(x) {
  min1 <- min(x)
  min2 <- min(x[x != min(x)])
  min3 <- -sort(-x, TRUE)[3]
  cmin <- c(min1, min2, min3)
  return(cmin)
}

Upvotes: 1

Views: 716

Answers (1)

dcarlson
dcarlson

Reputation: 11056

Here's one way. First provide reproducible data:

set.seed(42)
X <- sample.int(20, 20)
X
# [1] 17  5  1 10  4  2 20 18  8  7 16  9 19  6 14 15 12  3 13 11

Now the indices of the bottom 3:

head(order(X), 3)
# [1]  3  6 18
X[head(order(X), 3)]
# [1] 1 2 3

To create a function:

which.mins <- function(x, mins=3) {
    head(order(x), mins)
}
which.mins(X, 3)
# [1]  3  6 18
which.mins(X, 5)
# [1]  3  6 18  5  2

Upvotes: 4

Related Questions