count distinct values in an R vector

R – Count Distinct Values in a Vector

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

How do you count unique values in a vector in R?

You can use a combination of the length() and the unique() function in R to count the number of distinct (or unique) values in a vector.

First, use the unique() function to remove the duplicates and then apply the length() function to get the unique value count inside the vector. The following is the syntax –

# count distinct values in vector vec
length(unique(vec))

Note that the distinct value count from the above method is inclusive of NA values (if any) inside the vector. See the examples below.

Examples

Let’s now look at some examples of using the above method.

Count of distinct values in a vector

Let’s create a vector of some numbers (and having some repeated values) and use a combination of the length() and unique() functions to get its distinct value count.

# create a vector
vec <- c(1, 2, 3, 2, 3, 3)
# count distinct values in vec
print(length(unique(vec)))

Output:

[1] 3

We get 3 as the output since there are only three distinct values in the above vector – 1, 2, and 3.

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

Count of distinct values in a vector with NA values

What would happen if our vector contains some NA values?

Let’s find out.

We’ll use the same vector from above with some additional NA values and then apply the same method.

# create a vector
vec <- c(1, 2, NA, 3, 2, 3, NA, 3)
# count distinct values in vec
print(length(unique(vec)))

Output:

[1] 4

Now, we get the unique value count as 4. This is because the unique() function removes duplicates and not NA. Thus we get four unique values – 1, 2, NA, and 3.

If you do not want to include NA in the unique value count, you can remove NA values from the vector before applying the above method.

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 Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top