Count the specific value in a given vector in R
Last Updated :
07 Apr, 2021
In this article, we will discuss how to find the specific value in a given vector in R Programming Language. For finding the frequency of a given value two approaches can be employed and both of them are discussed below.
Method 1: Naive method
We can iterate over the vector in R using a for loop and then check if the element is equivalent to the given value. A counter is maintained, and it is increased by 1, each time the value matches. In case, the element is not present, counter returns a value 0. The time complexity of the approach is O(n), where n is the size of the vector.
Example:
R
vec = c (1,2,3,4,2,1,4,6)
print ( "Original Vectors:" )
print (vec)
count = 0
x = 4
for ( i in vec){
if (vec[i]==x){
count= count + 1
}
}
print ( "Count given value in above vector:" )
print (count)
|
Output
[1] “Original Vectors:”
[1] 1 2 3 4 2 1 4 6
[1] “Count given value in above vector:”
[1] 2
Method 2: Using sum() method in R
The sum() method can be used to calculate the summation of the values appearing in the function argument. Here, we specify a logical expression as an argument of the sum() function which calculates the sum of values which are equivalent to the specified value. In case the value is not present, the sum method returns 0 as an output. The time complexity of the approach is O(n), where n is the size of the vector.
Syntax:
sum(vec == given_val)
where, vec is the vector and given_val is the given value to check the presence for in the vector.
Example:
R
vec = c ( "a" , "g" , "a" , "y" , "s" , "a" , "abcs" )
print ( "Original Vectors:" )
print (vec)
print ( "Count given value in above vector:" )
print ( sum (vec== "a" ))
|
Output
[1] “Original Vectors:”
[1] “a” “g” “a” “y” “s” “a” “abcs”
[1] “Count given value in above vector:”
[1] 3
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...