R Tutorial R Charts & Graphs R Statistics R References

R - sort() Function



The R sort() function returns a vector sorted into ascending or descending order. The syntax for using this function is given below:

Syntax

sort(x, decreasing = FALSE, na.last = NA)

Parameters

x Required. Specify a numeric, complex, character or logical vector to be sorted.
decreasing Optional. Specify whether the vector to be sorted in increasing or decreasing order. Default is increasing order.
na.last Optional. Specify the treatment of NA or NaN. If TRUE, missing values in the data are put last, if FALSE, they are put first, if NA, they are removed.

Return Value

Returns a vector sorted into ascending or descending order.

Example:

The example below shows the usage of sort() function.

vec <- c(10, 55, 25, -56, 30, 99)

cat("vec contains:", vec, "\n\n")
cat("vec sorted in increasing order:", sort(vec), "\n")
cat("vec sorted in decreasing order:", sort(vec, decreasing = TRUE), "\n")

m <- matrix(c(10, 55, 25, -56, 30, 99), ncol=2)
cat("\nThe matrix contains:\n")
print(m)
cat("\nSort all elements of matrix:", sort(m))
cat("\nSort all elements of first column:", sort(m[,1]))

The output of the above code will be:

vec contains: 10 55 25 -56 30 99 

vec sorted in increasing order: -56 10 25 30 55 99 
vec sorted in decreasing order: 99 55 30 25 10 -56 

The matrix contains:
     [,1] [,2]
[1,]   10  -56
[2,]   55   30
[3,]   25   99

Sort all elements of matrix: -56 10 25 30 55 99
Sort all elements of first column: 10 25 55

Using na.last parameter

The na.last parameter can be used to for the treatment of NA or NaN values in the vector. If it is TRUE, missing values in the data are put last, if set FALSE, they are put first, if set NA, they are removed.

Example:

Consider the example below to see the usage of na.last parameter.

vec <- c(10, 55, 25, -56, NaN, 30, 99, NA, NA)

cat("vec contains:", vec, "\n\n")
cat("vec sorted with NA first:", sort(vec, na.last = TRUE), "\n")
cat("vec sorted with NA last:", sort(vec, na.last = FALSE), "\n")
cat("vec sorted with NA removed:", sort(vec, na.last = NA), "\n")

The output of the above code will be:

vec contains: 10 55 25 -56 NaN 30 99 NA NA 

vec sorted with NA first: -56 10 25 30 55 99 NaN NA NA 
vec sorted with NA last: NaN NA NA -56 10 25 30 55 99 
vec sorted with NA removed: -56 10 25 30 55 99 

❮ R Statistical Functions