# How to reverse a vector in R (meet the rev function)

When working with data, it is sometimes necessary to reverse the order in which that data is processed or viewed. In R programming there is a simple function for carrying out this task, that makes it extremely easy.

## Meet the Reverse Function

In R programming you use the reverse function when reversing the order of a vector. It has the format of rev(x) where x is the name of the vector to be reversed. Because it has only a single argument, you are unlikely to encounter any problems using this function, unless you try to give it a variable name that does not exist then you will get an error message.

## How the Reverse Function Works

When you use the reverse function, it simply takes the vector that you give it and produces another vector consisting of the same values but in the reverse order of the original. It works on any vector. It will even reverse the column order on a data frame. You can even reverse the order of the data in an individual column of a data frame. This means that this function has a wide range of flexibility in its use.

## Examples

Here are four examples of the reverse function in action. Each one shows it being used under a different situation and with a different length vector.

> x = 1:12
> y = rev(x)
> x
 1 2 3 4 5 6 7 8 9 10 11 12
> y
 12 11 10 9 8 7 6 5 4 3 2 1

This is a simple example using a vector consisting of twelve consecutive integers. The reverse function is then used to reverse the order.

> x = c(“a”, “b”, “c”, “d”, “e”, “f”, “g”)
> y = rev(x)
> x
 “a” “b” “c” “d” “e” “f” “g”
> y
 “g” “f” “e” “d” “c” “b” “a”

In this example, we use a vector consisting of the first seven letters of the English alphabet. This sequence of a to g is then reversed producing a vector whose sequences g to a.

> t = as.numeric(Sys.time())
> set.seed(t)
> x = as.integer(abs(rnorm(10)*10))
> y = rev(x)
> x
 5 4 7 14 6 2 6 0 3 12
> y
 12 3 0 6 2 6 14 7 4 5

In this example, we have a sequence of ten random numbers. The sequence is then reversed to illustrate how well it works on any vector.

## How To Apply This Information

A major application of the reverse function is a way of double-checking a sequence of calculations. This is done by doing them in the reverse order to see if you get the same results but in the reverse order. This is the result you should get if your calculations are independent of one another.

Reversing the order of a vector in R programming is a simple process that has multiple applications. This simple function works not only on vectors but on data frames as well. It is a useful tool to have in your programming toolbox.

Scroll to top