Count the number of occurrences of a value in R

If I have a vector of numbers in R.

numbers <- c(1,1, 2,2,2, 3,3, 4,4,4,4, 1)

I want to return a vector that provides the number of times this value happened cumulatively along the vector. I.e.

results <- c(1,2, 1,2,3, 1,2, 1,2,3,4, 3)
+4
source share
1 answer

We can use aveand apply seq_alongby grouping with "numbers"vector

ave(numbers, numbers, FUN = seq_along)
#[1] 1 2 1 2 3 1 2 1 2 3 4 3
+10
source

Source: https://habr.com/ru/post/1689319/


All Articles