当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


R语言 rev()用法及代码示例


R语言中的rev()函数用于返回数据对象的反向版本。数据对象可以定义为向量、按列和按行的 DataFrame 等。

用法: rev(x)

参数:
x:数据对象

返回:传递的数据对象的反转

范例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



相关用法


注:本文由纯净天空筛选整理自kaurbal1698大神的英文原创作品 Reverse the values of an Object in R Programming – rev() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。