R rev() Function - Reversing Vectors
The R rev() function is used to reverse the order of elements in a vector.
It turns the last element of a vector into the first, and the first into the last.
The syntax of the rev() function is as follows:
rev(x)
Parameter Description:
-
x Input vector.
Example
Reverse a numeric vector
x
<-
1
:
10
(
"Original vector:"
)
(
x
)
(
"After reversing:"
)
(
rev
(
x
)
)
Reverse a character vector
months
<-
month.abb
[
1
:
6
]
Abbreviations of the first 6 months
(
"First 6 months:"
)
(
months
)
(
"Reversed:"
)
(
rev
(
months
)
)
The output of the code above is:
[1] "原始向量:"
[1] 1 2 3 4 5 6 7 8 9 10
[1] "反转后:"
[1] 10 9 8 7 6 5 4 3 2 1
[1] "前 6 个月:"
[1] "Jan" "Feb" "Mar" "Apr" "May" "Jun"
[1] "反转:"
[1] "Jun" "May" "Apr" "Mar" "Feb" "Jan"
rev() combined with cumsum() can achieve different directions of cumulative computation:
Example
x
<-
c
(
10
,
20
,
30
,
40
,
50
)
Forward accumulation
(
"Forward accumulation:"
)
(
cumsum
(
x
)
)
Reverse accumulation (accumulating from the end backwards)
(
"Reverse accumulation:"
)
(
rev
(
cumsum
(
rev
(
x
)
)
)
)
The output of the code above is:
[1] "正向累加:"
[1] 10 30 60 100 150
[1] "反向累加:"
[1] 150 140 120 90 50
R Language Examples