Sorting a vector means arranging a given vector either alphabetically or numerically.
To perform this operation in R, we use the sort()
function.
sort(x)
The sort()
function takes a single parameter value, which is the vector object that is passed to it.
The sort()
function returns the vector object with its items arranged either alphabetically or numerically.
# creating vector variablesmy_vector1 <- c("banana", "apple", "orange", "mango", "lemon")my_vector2 <- c(10, 8, 9, 4, 7, 5, 1, 3, 6, 2)# using the sort() functionsort(my_vector1)sort(my_vector2)
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.