Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining minimum values in a vector in R

Tags:

r

I need some help in determining more than one minimum value in a vector. Let's suppose, I have a vector x:

x<-c(1,10,2, 4, 100, 3)

and would like to determine the indexes of the smallest 3 elements, i.e. 1, 2 and 3. I need the indexes of because I will be using the indexes to access the corresponding elements in another vector. Of course, sorting will provide the minimum values but I want to know the indexes of their actual occurrence prior to sorting.

like image 906
Shahzad Avatar asked Nov 19 '12 17:11

Shahzad


2 Answers

In order to find the index try this

which(x %in% sort(x)[1:3])  # this gives you and index vector
[1] 1 3 6

This says that the first, third and sixth elements are the first three lowest values in your vector, to see which values these are try:

x[ which(x %in% sort(x)[1:3])]  # this gives the vector of values
[1] 1 2 3

or just

x[c(1,3,6)]
[1] 1 2 3

If you have any duplicated value you may want to select unique values first and then sort them in order to find the index, just like this (Suggested by @Jeffrey Evans in his answer)

which(x %in% sort(unique(x))[1:3])
like image 196
Jilber Urbina Avatar answered Oct 02 '22 00:10

Jilber Urbina


I think you mean you want to know what are the indices of the bottom 3 elements? In that case you want order(x)[1:3]

like image 27
frankc Avatar answered Oct 02 '22 00:10

frankc