Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Count the specific value in a given vector in R

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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




# declaring a vector
vec = c(1,2,3,4,2,1,4,6)
  
# printing original vector
print("Original Vectors:")
print(vec)
  
# declaring count = 0 
count = 0
  
# given value
x = 4
  
# looping over vector values
for( i in vec){
    
    # check if the value is equal to x
    if(vec[i]==x){
        
        # increment counter by 1 
        count= count + 1
    }
}
  
print("Count given value in above vector:")
  
# check which values are equal to the given 
# value and calculate sum of it
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




# declaring a vector
vec = c("a","g","a","y","s","a","abcs")
  
# printing original vector
print("Original Vectors:")
print(vec)
  
print("Count given value in above vector:")
  
# check which values are equal to the given 
# value and calculate sum of it
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


My Personal Notes arrow_drop_up
Last Updated : 07 Apr, 2021
Like Article
Save Article
Similar Reads
Related Tutorials