Home > Mobile >  Finding the indexes of the smallest 3 elements in a subsetted vector
Finding the indexes of the smallest 3 elements in a subsetted vector

Time:06-20

I have the following vector a:

a<-c(100, 84, 126, 336, 544, 0, 2176)

I want to subset a using the following index vector `b:

b<-c(1,2,4,5,7)

In this case, the subset would be:

a[b]=c(100,84,336,544,3276)

From this subset of a I want to take the smallest three numbers. I then want to know what indexes of a these smallest three numbers are.

The smallest 3 numbers in this subset would be:

c(84,100,336)

So the indexes of these numbers in a would be:

result<-c(2,1,4)

How can I get to this final result?

CodePudding user response:

If efficiency is not important:

match(sort(a[b])[1:3], a)
# [1] 2 1 4

A bit faster:

match(sort(a[b], partial = 1:3)[1:3], a)

A bit cleaner:

intersect(order(a), b)[1:3]
  • Related