Open In App

R Program to reverse a number – rev() Function

Last Updated : 20 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to reverse a number in R Programming Language. To reverse a number we will use in built method in R.

In R Programming Language rev() function 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

R program to reverse a number

R




# 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

R program to Reverse Columns of a Data Frame

R




# 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

R program to Reverse Rows of a Data Frame

R




# 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

data_rev_row_a
x1 x2 x3
[1,] 5 10 15
[2,] 4 9 14
[3,] 3 8 13
[4,] 2 7 12
[5,] 1 6 11
data_rev_row_b
x1 x2 x3
5 5 10 15
4 4 9 14
3 3 8 13
2 2 7 12
1 1 6 11

Conclusion

The rev function provides a concise and efficient solution for reversing the elements of a vector. It is particularly useful in scenarios where the order of elements needs to be reversed for further analysis or presentation.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads