how to filter and reverse the values using vector
How to filtering vector values
Method 1: Using %in%
Here we can filter the
elements in a vector by using the %in% operator
Syntax:
vec[vec %in%
c(elements)]
where
·
vec is the input vector
·
elements are the vector
elements that we want to get
Example: R program to filter the vector by getting only
some values
# create a vector with id and names
vector=c(1,2,3,4,5,"sravan","boby","ojaswi","gnanesh","rohith")
# display vector
print(vector)
print("=======")
# get the data - "sravan","rohith",3 from
# the vector
print(vector[vector %in%
c("sravan","rohith",3)])
print("=======")
# get the data - "sravan","ojaswi",3,1,2 from
# the vector
print(vector[vector %in%
c("sravan","ojaswi",3,1,2)])
print("=======")
# get the data - 1,2,3,4,5 from the vector
print(vector[vector %in% c(1,2,3,4,5)])
Method 2: Using Index
We can also specify the condition
from the index operator.
Syntax:
vector[condition(s)]
where
the vector is the input vector and condition defines the condition to follow
for filtering.
Example: R program to
filter vector using the conditions
# create a vector with id and names
vector=c(1,2,3,4,5,"sravan","boby","ojaswi","gnanesh","rohith")
# display vector
print(vector)
print("=======")
# get the data where element not equal to 1
print(vector[vector != 1])
print("=======")
# get the data where element equal to 1
print(vector[vector == 1])
How to reverse the order of given vector in R?
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
# 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)
# 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)
Comments
Post a Comment