Sort elements of an Object by its Index Values in R Programming – order() function

order() function in R Language is used to sort an object by its index value. These objects can be vector, matrix or data frames. This function accepts boolean value as argument to sort in ascending or descending order.

Syntax:
order(x, decreasing, na.last)

Parameters:
x: Vector to be sorted
decreasing: Boolean value to sort in descending order
na.last: Boolean value to put NA at the end

Example 1:




# R program to sort a vector by index values
  
# Creating a vector
x <- c(7, 4, 3, 9, 1.2, -4, -5, -8, 6, NA)
  
# Calling order() function
order(x)


Output:

[1]  8  7  6  5  3  2  9  1  4 10

Example 2:




# R program to sort a vector by index values
  
# Creating a vector
x <- c(7, 4, 3, 9, 1.2, -4, -5, -8, 6, NA)
  
# Calling order() function
# to sort in decreasing order
order(x, decreasing = TRUE)
  
# Calling order() function
# to print NA at the end
order(x, na.last = TRUE)


Output:

 [1]  4  1  9  2  3  5  6  7  8 10
 [1]  8  7  6  5  3  2  9  1  4 10