Related Tags

r
vector
sort()
communitycreator

# How to sort a vector in R Onyejiaku Theophilus Chidalu

### Overview

Sorting a vector means arranging a given vector either alphabetically or numerically.

To perform this operation in R, we use the sort() function.

### Syntax

sort(x)


### Parameter

The sort() function takes a single parameter value, which is the vector object that is passed to it.

### Return value

The sort() function returns the vector object with its items arranged either alphabetically or numerically.

### Code example

# creating vector variables
my_vector1 <- c("banana", "apple", "orange", "mango", "lemon")
my_vector2 <- c(10, 8, 9, 4, 7, 5, 1, 3, 6, 2)

# using the sort() function
sort(my_vector1)
sort(my_vector2)
Implementing the "sort()" function

### Code explanation

• Lines 2–3: We create two vectors, which are of type string and numeric.

• Lines 5–6: We call the sort() function to sort those two vectors.

We can see that we are able to arrange the items of the vector objects, my_vector1 and my_vector2), alphabetically and numerically with the help of the sort() function.

RELATED TAGS

r
vector
sort()
communitycreator

CONTRIBUTOR Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time 