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? 回答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)