user5946647
user5946647

Reputation:

Count frequency of each element in vector

I'm looking for a way to count the frequency of each element in a vector.

ex <- c(2,2,2,3,4,5)

Desired outcome:

[1] 3 3 3 1 1 1

Is there a simple command for this?

Upvotes: 1

Views: 4452

Answers (2)

JohnM
JohnM

Reputation: 164

You can use

ex <- c(2,2,2,3,4,5)    
outcome <- ave(ex, ex, FUN = length)

This is what thelatemail suggested. Also similar to the answer at this question

Upvotes: 1

Gregor Thomas
Gregor Thomas

Reputation: 145755

rep(table(ex), table(ex))
# 2 2 2 3 4 5 
# 3 3 3 1 1 1 

If you don't want the labels you can wrap in as.vector()

as.vector(rep(table(ex), table(ex)))
# [1] 3 3 3 1 1 1

I'll add (because it seems related somehow) that if you only wanted consecutive values, you could use rle instead of table:

ex2 = c(2, 2, 2, 3, 4, 2, 2, 3, 4, 4)
rep(rle(ex2)$lengths, rle(ex2)$lengths)
# [1] 3 3 3 1 1 2 2 1 2 2

As pointed out in comments, for a large vector calculating a table can be expensive, so doing it only once is more efficient:

tab = table(ex)
rep(tab, tab)
# 2 2 2 3 4 5 
# 3 3 3 1 1 1 

Upvotes: 3

Related Questions