2

I am starting with "Start"

ID <- c("A", "A", "A", "B", "B", "C")
Lab <- c("5", "10", "15", "20", "5", "10")
Date <- as.Date(c("01/01/2020",
          "01/01/2020",
          "01/02/2020",
          "01/01/2020",
          "01/02/2020",
          "01/05/2020"), format="%m/%d/%Y")
Start <- data.frame(ID, Lab, Date)
Start
#>   ID Lab       Date
#> 1  A   5 2020-01-01
#> 2  A  10 2020-01-01
#> 3  A  15 2020-01-02
#> 4  B  20 2020-01-01
#> 5  B   5 2020-01-02
#> 6  C  10 2020-01-05

and need to get to "Finish".

Day <- c(1, 1, 2, 1, 2, 1)
Finish <- data.frame(ID, Lab, Date, Day)
Finish
#>   ID Lab       Date Day
#> 1  A   5 2020-01-01   1
#> 2  A  10 2020-01-01   1
#> 3  A  15 2020-01-02   2
#> 4  B  20 2020-01-01   1
#> 5  B   5 2020-01-02   2
#> 6  C  10 2020-01-05   1

Every ID will have multiple Labs per day, across several days. I need a new variable, "Day", that reflects the day the lab was drawn, incremented by 1 every time the date changes, and resetting the day to "1" when the patient ID changes.

Created on 2020-04-16 by the reprex package (v0.3.0)

dr_canak
  • 55
  • 3
  • I reopened it because the [link](https://stackoverflow.com/questions/23197594/r-create-id-within-a-group) doesn't seem to be answering the question – akrun Apr 16 '20 at 21:49

1 Answers1

0

We can use cumsum on a logical vector to create the 'Day' after grouping by 'ID'

library(dplyr)
Start %>% 
      group_by(ID) %>% 
      mutate(Day = cumsum(!duplicated(Date)))
# A tibble: 6 x 4
# Groups:   ID [3]
#  ID    Lab   Date         Day
#  <fct> <fct> <date>     <int>
#1 A     5     2020-01-01     1
#2 A     10    2020-01-01     1
#3 A     15    2020-01-02     2
#4 B     20    2020-01-01     1
#5 B     5     2020-01-02     2
#6 C     10    2020-01-05     1
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Good deal! I had googled around, and found multiple dead ends, as I didn't see this particular scenario. Thank you so much for the quick solution. Works great. – dr_canak Apr 16 '20 at 23:49