To sort table in R there are two methods in R.

The following methods show how you can do it with syntax.

Method 1: Use order() Function

# Sort in ascending order
order(x)

# Sort in descending order
order(x,decreasing=TRUE)


Method 2: Use sort() Function

# Sort in ascending order
sort(x)

# Sort in descending order
sort(x,decreasing=TRUE)


The following examples show how to use these function in R.

## Use order() Function to Sort Table in Ascending Order

Let’s see how we can use order() function in R:

# Create table
table_1 <- c(78,89,85,84,81,79,77,85)

# Sort table in ascending order
sorted_table <- table_1[order(table_1)]

# Print sorted table
print(sorted_table)


Output:

[1] 77 78 79 81 84 85 85 89


Here in the output it shows sorted table in ascending order.

## Use order() Function to Sort Table in Descending Order

Let’s see example to sort table in descending order:

# Create table
table_1 <- c(78,89,85,84,81,79,77,85)

# Sort table in descending order
sorted_table <- table_1[order(table_1,decreasing=TRUE)]

# Print sorted table
print(sorted_table)


Output:

[1] 89 85 85 84 81 79 78 77


As output shows table is sorted in descending order using order() function.

## Use sort() Function to Sort Table in Ascending Order

Suppose we want to sort table in ascending order using sort() function:

# Create table
table_1 <- c(78,89,85,84,81,79,77,85)

# Sort table in ascending order
sorted_table <- sort(table_1)

# Print sorted table
print(sorted_table)


Output:

[1] 77 78 79 81 84 85 85 89


As output shows values are sorted in ascending order using sort() function.

## Use sort() Function to Sort Table in Descending Order

Let’s see how to sort table in descending order using sort() function:

# Create table
table_1 <- c(78,89,85,84,81,79,77,85)

# Sort table in ascending order
sorted_table <- sort(table_1,decreasing=TRUE)

# Print sorted table
print(sorted_table)


Output:

[1] 89 85 85 84 81 79 78 77


As output shows values are sorted in descending order using sort() function.