How to add a counter to each group in dplyr

Hi,

I think this StackOverflow thread will get you what you're looking for

In the future it's easier to answer a question if you include self-contained reprex (short for reproducible example). For pointers specific to the community site, check out the reprex FAQ.

Edit: Leaving below for posterity, but definitely use @mishabalyasin's with row_number() (which is also what at least one answer suggests in the SO thread, I think). (>ლ)

library(tidyverse)
mydata <- data_frame(countries = c("France", "US", "France", "France", "China", "China", "US"),
                     number = 1)

mydata %>%
  group_by(countries) %>%
  mutate(ticker = cumsum(number))
#> # A tibble: 7 x 3
#> # Groups:   countries [3]
#>   countries number ticker
#>   <chr>      <dbl>  <dbl>
#> 1 France         1      1
#> 2 US             1      1
#> 3 France         1      2
#> 4 France         1      3
#> 5 China          1      1
#> 6 China          1      2
#> 7 US             1      2

Created on 2018-08-22 by the reprex package (v0.2.0.9000).

3 Likes