Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R rev() Function - Reversing Vectors

R rev() Function - Reversing Vectors

R Language Examples R Language Examples

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:

Example

Reverse a numeric vector

x

<-

1

:

10

print

(

"Original vector:"

)

print

(

x

)

print

(

"After reversing:"

)

print

(

rev

(

x

)

)

Reverse a character vector

months

<-

month.abb

[

1

:

6

]

 

Abbreviations of the first 6 months

print

(

"First 6 months:"

)

print

(

months

)

print

(

"Reversed:"

)

print

(

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

print

(

"Forward accumulation:"

)

print

(

cumsum

(

x

)

)

Reverse accumulation (accumulating from the end backwards)

print

(

"Reverse accumulation:"

)

print

(

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 R Language Examples