在 R 编程中反转对象的值 - rev()函数
R 语言中的rev()
函数用于返回数据对象的反向版本。数据对象可以定义为向量、按列和按行的数据框等。
Syntax: rev(x)
Parameter:
x: Data object
Returns: Reverse of the data object passed
示例 1:
# R program to reverse a vector
# Create a vector
vec <- 1:5
vec
# Apply rev() function to vector
vec_rev <- rev(vec)
vec_rev
输出:
[1] 1 2 3 4 5
[1] 5 4 3 2 1
示例 2:数据框的反转列
# R program to reverse
# columns of a Data Frame
# Creating a data.frame
data <- data.frame(x1 = 1:5,
x2 = 6:10,
x3 = 11:15)
data
# Print reversed example data frame
data_rev <- rev(data)
data_rev
输出:
x1 x2 x3
1 1 6 11
2 2 7 12
3 3 8 13
4 4 9 14
5 5 10 15
x3 x2 x1
1 11 6 1
2 12 7 2
3 13 8 3
4 14 9 4
5 15 10 5
示例 3:数据帧的反向行
# R program to reverse
# rows of a data frame
# Creating a data frame
data <- data.frame(x1 = 1:5,
x2 = 6:10,
x3 = 11:15)
data
# Calling rev() & apply() functions combined
data_rev_row_a <- apply(data, 2, rev)
data_rev_row_a
# Alternative without rev()
data_rev_row_b <- data[nrow(data):1, ]
data_rev_row_b
输出:
x1 x2 x3
1 1 6 11
2 2 7 12
3 3 8 13
4 4 9 14
5 5 10 15
x1 x2 x3
[1,] 5 10 15
[2,] 4 9 14
[3,] 3 8 13
[4,] 2 7 12
[5,] 1 6 11
x1 x2 x3
5 5 10 15
4 4 9 14
3 3 8 13
2 2 7 12
1 1 6 11