Explore Courses Blog Tutorials Interview Questions
+1 vote
in R Programming by (5.3k points)

Let's say I have:

v = rep(c(1,2, 2, 2), 25)

Now, I want to count the number of times each unique value appears. unique(v) returns what the unique values are, but not how many they are.


[1] 1 2

I want something that gives me


[1] 25


[1] 75 

but as a more general one-liner :) Something close (but not quite) like this:

#<doesn't work right> length(v[v==unique(v)]) 

2 Answers

+1 vote

To count unique values, you can use the table function that creates a frequency table to calculate the occurrences of unique values of a variable.

The table() function generates an object of the table class.

For example:


freq.table <- table(iris$Species)


    setosa versicolor  virginica 

        50         50         50 

In your case:

v = rep(c(1,2, 2, 2), 25)



 1  2 

25 75 

To convert the table to a data frame:

  v Freq

1 1   25

2 2   75

A one-line approach:[,2]

[1] 25 75

If you want to explore more in R programming then watch this R programming tutorial for beginner:

0 votes
by (32.3k points)

Let's say we have the following data frame:

> myvec

    name order_no

1    Amy     12

2   Jack       14

3   Jack       16

4   Dave       11

5    Amy     12

And you want to count the number of distinct order_no values for each name. 

In such case you can simply do:


P.S. - Keep in mind that this approach requires package plyr.

Related questions

+1 vote
2 answers
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

29.3k questions

30.6k answers


104k users

Browse Categories