To iterate over a vector in reverse order in R, you can use the rev
function to reverse the vector first, then iterate over it using a for loop or one of the apply functions.
In this example,
num_vec
with several numeric values.rev
function to reverse the order of elements in num_vec
.for
loop, starting from the first element (which was the last element before reversal) to the last element.num_vec <- c(10, 20, 30, 40, 50)
reversed_num_vec <- rev(num_vec)
for (num in reversed_num_vec) {
print(num)
}
[1] 50 [1] 40 [1] 30 [1] 20 [1] 10
In this example,
char_vec
with several string values.rev
function to reverse the order of elements in char_vec
.sapply
function, which applies a function to each element of the vector.sapply
function, we define an anonymous function that prints each element of the vector. This effectively traverses the vector in reverse order.char_vec <- c("apple", "banana", "cherry", "date")
reversed_char_vec <- rev(char_vec)
sapply(reversed_char_vec, function(x) print(x))
[1] "date" [1] "cherry" [1] "banana" [1] "apple"
In this tutorial, we learned How to Iterate Over a Vector in Reverse Order in R language with well detailed examples.