How to reverse the order of given vector in R?
In this article, we will discuss how to reverse the order of elements in a vector in R Programming Language.
It can be done using the rev() function. It returns the reverse version of data objects.
Syntax: rev(x)
Parameter: x: Data object
Returns: Reverse of the data object passed
Example 1: Here we will create a vector and reverse it with rev() function.
R
# create vector with names vec = c ( "sravan" , "mohan" , "sudheer" , "radha" , "vani" , "mohan" ) print ( "Original vector-1:" ) print (vec) rv = rev (vec) print ( "The said vector in reverse order:" ) print (rv) |
Output:
[1] “Original vector-1:”
[1] “sravan” “mohan” “sudheer” “radha” “vani” “mohan”
[1] “The said vector in reverse order:”
[1] “mohan” “vani” “radha” “sudheer” “mohan” “sravan”
Example 2: Here we will create multiple vectors and then reverse them.
R
# create vector with names name = c ( "sravan" , "mohan" , "sudheer" , "radha" , "vani" , "mohan" ) # create vector with subjects subjects = c ( ".net" , "Python" , "java" , "dbms" , "os" , "dbms" ) # create a vector with marks marks = c (98, 97, 89, 90, 87, 90) # create vector with height height = c (5.97, 6.11, 5.89, 5.45, 5.78, 6.0) # create vector with weight weight = c (67, 65, 78, 65, 81, 76) # pass these vectors to the vector data = c (name, subjects, marks, height, weight) # display print ( "Original vector-1:" ) print (data) rv = rev (data) print ( "The said vector in reverse order:" ) print (rv) |
Output:
[1] “Original vector-1:”
[1] “sravan” “mohan” “sudheer” “radha” “vani” “mohan” “.net”
[8] “Python” “java” “dbms” “os” “dbms” “98” “97”
[15] “89” “90” “87” “90” “5.97” “6.11” “5.89”
[22] “5.45” “5.78” “6” “67” “65” “78” “65”
[29] “81” “76”
[1] “The said vector in reverse order:”
[1] “76” “81” “65” “78” “65” “67” “6”
[8] “5.78” “5.45” “5.89” “6.11” “5.97” “90” “87”
[15] “90” “89” “97” “98” “dbms” “os” “dbms”
[22] “java” “Python” “.net” “mohan” “vani” “radha” “sudheer”
[29] “mohan” “sravan”