R rev() Function - Reverse a Vector

R 语言实例R Language Examples

The R rev() function is used to reverse the order of elements in a vector.

It turns the last element of the vector into the first, and the first into the last.

The syntax of the rev() function is as follows:

rev(x)

Parameter description:

  • xInput vector.

Example

# Reverse numeric vector
x <- 1:10
print("Original vector:")
print(x)
print("After reversal:")
print(rev(x))

# Reverse character vector
months <- month.abb[1:6]  # Abbreviations of the first 6 months
print("First 6 months:")
print(months)
print("Reversed:")
print(rev(months))

Executing the above code produces the following output:

[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"

Combining rev() with cumsum() can achieve different cumulative calculation directions:

Example

x <- c(10, 20, 30, 40, 50)

# Forward cumulative sum
print("Forward cumulative sum:")
print(cumsum(x))

# Reverse cumulative sum (accumulate from the end backwards)
print("Reverse cumulative sum:")
print(rev(cumsum(rev(x))))

Executing the above code produces the following output:

[1] "正向累加:"
[1]  10  30  60 100 150
[1] "反向累加:"
[1] 150 140 120  90  50

R 语言实例R Language Examples

Other Extensions