Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting the number of occurrences of a value in R [duplicate]

Tags:

r

vector

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 that value has occurred cumulatively along the vector. I.e.

results <- c(1,2, 1,2,3, 1,2, 1,2,3,4, 3)
like image 731
falcs Avatar asked Dec 24 '22 12:12

falcs


1 Answers

We can use ave and apply the seq_along by grouping with the 'numbers' vector

ave(numbers, numbers, FUN = seq_along)
#[1] 1 2 1 2 3 1 2 1 2 3 4 3
like image 166
akrun Avatar answered Mar 08 '23 23:03

akrun