Skip to Content

R – Count Occurrences of a Value in a Vector

In this tutorial, we will look at how to count the number of times a value occurs in a vector in R with the help of some examples.

How to count element frequency in a vector in R?

In R, you can use a combination of the length() function and logical indexing to count the occurrence of a value in a vector. The following are the steps –

  1. Filter the vector such that it includes only the value that you want to compute the frequency for.
  2. Apply the length() function on the filtered vector to determine the count of the value inside the vector.

The following is the syntax –

# count of value val in the vector vec
length(vec[vec == 2])

Here, we get the count of the value val in the vector vec.

Examples

Let’s now use some examples of using the above syntax to compute the count of a value inside a vector.

Count value occurrences in a vector

To count the occurrences of a value, we first filter the vector using a logical expression such that other values are removed and then use the length() function to determine its count.

# create a vector
vec <- c(1, 4, 3, 2, 2, 3, 2)
# count of 2 in vec
print(length(vec[vec == 2]))

Output:

[1] 3

Here, we create a vector of some numbers and count the occurrences of the number 2.

The expression vec[vec == 2] gives a vector by removing all elements other than 2 from the vector vec. You can see that we get its count as 3 because 2 occurs 3 times in our vector.

Count occurrences of each value in a vector

You can also use the above method to count the occurrences of each value in the vector but in that case, you’ll have to use the method on each unique value separately.

Alternatively, you can use the table() function in R to compute the count of each value in a vector.

Let’s see an example. We’ll apply the table() function to the same vector used in the above example.

# create a vector
vec <- c(1, 4, 3, 2, 2, 3, 2)
# count of each value in vec
print(table(vec))

Output:

vec
1 2 3 4 
1 3 2 1 

We get the frequency of each element in the vector. You can see that 1 and 4 occur once, 2 occurs three times and 3 occurs two times in the above vector.

Let’s look at another example. This time we’ll use character values in the vector.

# create a vector
vec <- c('a', 'b', 'a', 'c', 'c', 'c', 'd')
# count of each value in vec
print(table(vec))

Output:

vec
a b c d 
2 1 3 1 

We get the count of each value in the above vector.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush

    Piyush is a data scientist passionate about using data to understand things better and make informed decisions. In the past, he's worked as a Data Scientist for ZS and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.