Sorting elements
There are mainly two functions in the base R package (that is, the package that comes by default when installing R) to display ordered elements—sort()
and order()
.
sort()
: This is a function that returns the passed vector in decreasing or increasing order:> vector1 <- c(2,5,3,4,1) > sort(vector1) [1] 1 2 3 4 5
If the vector passed is of the character type, the function returns it in alphabetical order and if it is logical, it will first return the
FALSE
elements and then theTRUE
elements:> sort(c(T,T,F,F)) [1] FALSE FALSE TRUE TRUE
order()
: This returns the index number of the ordered elements according to their values:> vector1 <- c(2,5,3,4,1) > order(vector1) [1] 5 1 3 4 2
In the preceding example, for the
vector1
object, the function returns the fifth element first, then the first, then the third, and so on. For character or logical vectors, the criterion is the same as insort()
:> sort(vector1,decreasing=T) [1] 5 4 3 2 1
Tip
To return elements...