Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Reverse the values of an Object in R Programming – rev() Function

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

rev() function in R Language is used to return the reverse version of data objects. The data objects can be defined as Vectors, Data Frames by Columns & by Rows, etc.

Syntax: rev(x)

Parameter:
x: Data object

Returns: Reverse of the data object passed

Example 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                                  


Output:

[1] 1 2 3 4 5
[1] 5 4 3 2 1

Example 2: Reverse Columns of a Data Frame




# 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


Output:

   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

Example 3: Reverse Rows of a Data Frame




# 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


Output:

  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

My Personal Notes arrow_drop_up
Last Updated : 17 Jun, 2020
Like Article
Save Article
Similar Reads