Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
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.

 unique(v)

[1] 1 2

I want something that gives me

length(v[v==1])

[1] 25

length(v[v==2])

[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
by
edited

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:

data(iris)

freq.table <- table(iris$Species)

 head(freq.table)

    setosa versicolor  virginica 

        50         50         50 

In your case:

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

table(v)

v

 1  2 

25 75 

To convert the table to a data frame:

as.data.frame(table(v))

  v Freq

1 1   25

2 2   75

A one-line approach:

as.data.frame(table(v))[,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:

ddply(myvec,~name,summarise,number_of_distinct_orders=length(unique(order_no)))

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

Browse Categories

...