R – Reverse a Vector
To reverse a vector in R programming, call rev() function and pass given vector as argument to it. rev() function returns returns a new vector with the contents of given vector in reversed order.
The syntax to reverse a vector x
is
rev(x)
Return Value
The rev() function returns a vector.
Examples
In the following program, we take a vector in x
, and reverse this vector using rev().
example.R
x <- c(5, 10, 15, 20, 25, 30) result = rev(x) cat("Original Vector :", x, "\n") cat("Reversed Vector :", result)
Output
Original Vector : 5 10 15 20 25 30 Reversed Vector : 30 25 20 15 10 5
Now, let us take a vector x
with string items and reverse it.
example.R
x <- c("a", "b", "c") result = rev(x) cat("Original Vector :", x, "\n") cat("Reversed Vector :", result)
Output
Original Vector : a b c Reversed Vector : c b a
Conclusion
In this R Tutorial, we learned how to reverse a vector using rev() function, with the help of examples.