1

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?

2 Answers2

3
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 
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
1

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

JohnM
  • 144
  • 1
  • 10