I want to mutate the original df to add a column to calculate the days since the last math ("M") absence. I wanted the first occurrence of a student's math absence to be NA, and if there weren't any previous math absences, I wanted the value to be Inf.

I ordered the df by date and then wrote out this line of code:

df %>% groupby(Student\_ID) %>% mutate(dayssinceM = ifelse(Subject == "M", c(NA, diff(Absent\_Date)), Inf))

This worked until a student had a math absence later on in the data. I tried to add another ifelse statement: ifelse(lag(Subject == "M", c(NA, diff(Absent\_Date)), Inf)), but it only worked if the math absence was directly previously. I want it to be if the student had any math absence previously. I was thinking maybe adding rollapply somehow. I would love to hear your thoughts and get some help please.

Original df:

```
 Studen_ID       Absent_Date       Subject        

    4567           08/30/2018          M
    4567           09/22/2019          M
    8345           09/01/2019          SS
    8345           03/30/2019          S         
    8345           07/18/2017          S
    8345           01/08/2019          M

```

This is the desired output:

```
 Student_ID       Absent_Date       Subject         dayssinceM            

    4567           08/30/2018          M                 NA
    4567           09/22/2019          M                 388
    8345           07/18/2017          S                 Inf
    8345           01/08/2019          M                 NA        
    8345           03/30/2019          S                 81
    8345           09/01/2019         SS                 236

```