Sort a vector in R Programming Language

Sort a vector in R Programming Language

Sorting of vectors can be done using the sort() function. By default, it sorts in ascending order. To sort in descending order we can pass decreasing=TURE.
Note that sort is not in-place. This means that the original vector is not effected (sorted). Only a sorted version of it is returned.

x <- c( 1, 4, 3, 9, 6, 7) 
sort(x) //sort in ascending order
sort(x, decreasing=TRUE)//sort in descending order

out put:

$Rscript main.r
[1] 1 3 4 6 7 9
[1] 9 7 6 4 3 1

Or
Sometimes we would want the index of the sorted vector instead of the values. In such case we can use the function order().

x <- c( 1, 4, 3, 9, 6, 7) 
order(x)

output:
$Rscript main.r
[1] 1 3 2 5 6 4

(Or)
x <- c( 1, 4, 3, 9, 6, 7) 
order(x)
x[order(x)]

Output:

$Rscript main.r
[1] 1 3 2 5 6 4
[1] 1 3 4 6 7 9