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
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
name = c ( "sravan" , "mohan" , "sudheer" ,
"radha" , "vani" , "mohan" )
subjects = c ( ".net" , "Python" , "java" ,
"dbms" , "os" , "dbms" )
marks = c (98, 97, 89, 90, 87, 90)
height = c (5.97, 6.11, 5.89,
5.45, 5.78, 6.0)
weight = c (67, 65, 78,
65, 81, 76)
data = c (name, subjects, marks,
height, weight)
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”
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!