I am trying to run the following: for every id, create a new variable (v2), which is
"F"whengrp=1(grpis the run-length typeidbased on the variablephase),"S"whengrp<=2& within the runningid(grp) the variableqchanges,"T"whengrp>2& within the runningid(grp) the variableqchanges.
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")