0

I have the following dataframe:

df <- data.frame(
          id = c(1, 1, 1, 2, 2, 2, 3, 3, 3), 
          name = c("J", "Z", "X", "A", "J", "B", "R", "J", "X")
)

I would like to group_by(id), then create a counter column which increases the value for each subsequent instance/level of (name). The desired output would look like this...

  id name count
   1    J    1
   1    Z    1
   1    X    1
   2    A    1
   2    J    2
   2    B    1
   3    R    1
   3    J    3
   3    X    2

I assume it would be something that starts like this...

library(tidyverse) 

df %>%
    group_by(id) %>%  

But I'm not sure how I would implement that kind of counter...

Any help much appreciated.

mdb_ftl
  • 423
  • 2
  • 14

1 Answers1

1

actually you have to group by the "name" since you are looking to count that independ of the Id:

library(dplyr)

df %>% 
  dplyr::group_by(name) %>% 
  dplyr::mutate(count = dplyr::row_number()) %>%
  dplyr::ungroup()


# A tibble: 9 x 3
     id name  count
  <dbl> <chr> <int>
1     1 J         1
2     1 Z         1
3     1 X         1
4     2 A         1
5     2 J         2
6     2 B         1
7     3 R         1
8     3 J         3
9     3 X         2
DPH
  • 4,244
  • 1
  • 8
  • 18