當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。