0

I am trying to run the following: for every id, create a new variable (v2), which is

  • "F" when grp=1 (grp is the run-length type id based on the variable phase),
  • "S" when grp<=2 & within the running id (grp) the variable q changes,
  • "T" when grp>2 & within the running id (grp) the variable q changes.

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")
Anna
  • 177
  • 13
  • 2
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Mar 15 '21 at 19:03
  • your sample `v2` is length 8, but there are only 7 `ids` -- is that supposed to be the case? – tdy Mar 15 '21 at 19:47
  • Apologies, I missed that, I edited my question now :) – Anna Mar 16 '21 at 08:23

0 Answers0