Count frequency of each element in vector

孤人 提交于 2021-01-29 03:27:31

问题


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?


回答1:


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 



回答2:


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



来源:https://stackoverflow.com/questions/36523910/count-frequency-of-each-element-in-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!