Adding event numbers by value in Dplyr

I have a tibble of Study events grouped by ID (with dates for each event), and I'm looking to add a value for each identical event by ID.

mydata <- tibble(ID = list("AA", "AA", "AA", "GA", "GA", "GA","GA","GA","GA","GA",GA"),
EventDate = list("21-10-2010","23-10-2010", "01-11-2010","16-01-2015","17-01-2015","02-02-2015","09-02-2015","03-03-2015","16-03-2015","20-03-2015","03-04-2015")
Event = list("Intro","Scan","Report", "Intro","Scan","Report","Scan","Report","Other","Scan","Report)

So what I'd like to do is add a column with an event number for each scan by ID (so the Scan event would be marked as 1 for AA, and 1-3 respectively for GA)
I'd also like to then do the same for the report, while not losing any other of the events in the table

(apologies for the rubbish reprex, but cannot install the necessary packages for a decent one!)

Next time, please test your code before posting, your code does not produce a data frame as it is, having said that, is this what you are trying to do?

library(dplyr)

mydata <- data.frame(
  stringsAsFactors = FALSE,
                ID = c("AA","AA","AA","GA","GA",
                       "GA","GA","GA","GA","GA","GA"),
         EventDate = c("21-10-2010","23-10-2010",
                       "01-11-2010","16-01-2015","17-01-2015","02-02-2015",
                       "09-02-2015","03-03-2015","16-03-2015","20-03-2015",
                       "03-04-2015"),
             Event = c("Intro","Scan","Report",
                       "Intro","Scan","Report","Scan","Report","Other","Scan",
                       "Report")
)

mydata %>% 
    filter(Event == "Scan") %>% 
    group_by(ID) %>% 
    mutate(event_number = row_number()) %>% 
    right_join(mydata)
#> Joining, by = c("ID", "EventDate", "Event")
#> # A tibble: 11 x 4
#> # Groups:   ID [2]
#>    ID    EventDate  Event  event_number
#>    <chr> <chr>      <chr>         <int>
#>  1 AA    21-10-2010 Intro            NA
#>  2 AA    23-10-2010 Scan              1
#>  3 AA    01-11-2010 Report           NA
#>  4 GA    16-01-2015 Intro            NA
#>  5 GA    17-01-2015 Scan              1
#>  6 GA    02-02-2015 Report           NA
#>  7 GA    09-02-2015 Scan              2
#>  8 GA    03-03-2015 Report           NA
#>  9 GA    16-03-2015 Other            NA
#> 10 GA    20-03-2015 Scan              3
#> 11 GA    03-04-2015 Report           NA

Created on 2020-02-11 by the reprex package (v0.3.0.9001)

That looks exactly like it!

Thanks!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.