Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cumulative count of each value [duplicate]

I want to create a cumulative counter of the number of times each value appears.

e.g. say I have the column:

id  
1  
2  
3  
2  
2  
1  
2  
3

This would become:

id   count  
1     1  
2     1  
3     1  
2     2  
2     3  
1     2  
2     4  
3     2  

etc...

like image 792
user1165199 Avatar asked Apr 05 '12 13:04

user1165199


People also ask

Does count function count duplicate values?

You can count duplicate values using the COUNTIF function. In this tutorial, you will learn how to count duplicates using this function.


4 Answers

The ave function computes a function by group.

> id <- c(1,2,3,2,2,1,2,3)
> data.frame(id,count=ave(id==id, id, FUN=cumsum))
  id count
1  1     1
2  2     1
3  3     1
4  2     2
5  2     3
6  1     2
7  2     4
8  3     2

I use id==id to create a vector of all TRUE values, which get converted to numeric when passed to cumsum. You could replace id==id with rep(1,length(id)).

like image 102
Joshua Ulrich Avatar answered Oct 18 '22 13:10

Joshua Ulrich


Here is a way to get the counts:

id <- c(1,2,3,2,2,1,2,3)

sapply(1:length(id),function(i)sum(id[i]==id[1:i]))

Which gives you:

[1] 1 1 1 2 3 2 4 2
like image 33
Sacha Epskamp Avatar answered Oct 18 '22 13:10

Sacha Epskamp


The dplyr way:

library(dplyr)

foo <- data.frame(id=c(1, 2, 3, 2, 2, 1, 2, 3))
foo <- foo %>% group_by(id) %>% mutate(count=row_number())
foo

# A tibble: 8 x 2
# Groups:   id [3]
     id count
  <dbl> <int>
1     1     1
2     2     1
3     3     1
4     2     2
5     2     3
6     1     2
7     2     4
8     3     2

That ends up grouped by id. If you want it not grouped, add %>% ungroup().

like image 26
dfrankow Avatar answered Oct 18 '22 14:10

dfrankow


For completeness, adding a data.table way:

library(data.table)

DT <- data.table(id = c(1, 2, 3, 2, 2, 1, 2, 3))

DT[, count := seq(.N), by = id][]

Output:

   id count
1:  1     1
2:  2     1
3:  3     1
4:  2     2
5:  2     3
6:  1     2
7:  2     4
8:  3     2
like image 5
Jens Adamczak Avatar answered Oct 18 '22 13:10

Jens Adamczak