I am trying to run the following: for every id, create a new variable (v2), which is
- "F"when- grp=1(- grpis the run-length type- idbased on the variable- phase),
- "S"when- grp<=2& within the running- id(- grp) the variable- qchanges,
- "T"when- grp>2& within the running- id(- grp) the variable- qchanges.
My main issue here is how can I include a group_by() function or equivalent within case_when() ? I tried the following:
df<-df %>% 
      group_by(id) %>%
      mutate(grp = rleid(phase), v2 = case_when(phase == 'First' ~ 'F',
                                                      phase == 'Second' & grp <= 2 & group_by(phase)%>% any(q != lag(q))%>% ungroup() ~ 'S', phase == 'Lane change' &
                                                        grp > 2 & group_by(phase)%>% any(q != lag(q)) %>% ungroup()  ~ 'T')) 
But I get an error :
Error in UseMethod("group_by_") : no applicable method for 'group_by_' applied to an object of class "NULL"
Any ideas?
Dummy data:
id <- c(1,1,1,2,2,2,2)
phase <- c("First", "Second","Second", "First" , "Second","Second","Second")
q <- c(1,1,1,1,1,1,2)
df<-data.frame(id,phase,q)
Desired output:
v2<- c("F", NA, NA, "F", NA, NA, "S")
