๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

R Sorting Vectors

Sorting puts the items of a vector into a chosen order. The sort function returns a new vector in that order.

Sorting numbers

sort puts the numbers in rising order. The smallest number comes first.

print(sort(c(8, 3, 9, 1)))

Sorting in reverse order

The decreasing argument flips the sort around. The largest number now comes first.

print(sort(c(8, 3, 9, 1), decreasing = TRUE))

Sorting words

sort also arranges words in alphabetical order. The word apple comes first here.

print(sort(c("pear", "apple", "fig")))

Reversing without sorting

rev flips the order of the vector as it stands. sort then shows the same values arranged by size.

u <- c(5, 2, 8)
print(rev(u))
print(sort(u))

Positions that sort

order returns positions rather than values. The first position points at the smallest item.

v <- c(30, 10, 20)
print(v)
print(order(v))

Example

heights <- c(170, 155, 182, 160)
print(sort(heights))
print(sort(heights, decreasing = TRUE))

Key points

  • sort arranges numbers from the smallest to the largest.
  • The argument decreasing = TRUE arranges values from the largest to the smallest.
  • sort also arranges words in alphabetical order.
  • rev reverses the current order of a vector without sorting it.
  • Reversing an unsorted vector does not sort it.
  • order returns the positions that would sort a vector.
  • The first value from order is the position of the smallest item.

In this example, the heights are sorted into rising order first. The second call then sorts the same heights into falling order.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

What does rev(c(5, 2, 8)) print?