Let's say I have this data frame in R:
x <-data.frame(group=c("A","A","A", "B","B", "C","C","C"), cond=c("g1", "g2", "g1", "g3", "g2", "g2", "g1", "g2"), order=c(1,2,3,2,1,2,3,1))
group cond order
A g1 1
A g2 2
A g1 3
B g3 2
B g2 1
C g2 2
C g1 3
C g2 1
I want order groups according to the order variable to make two variables: v1) yes/no whether cond=="g1" for any of the previous rows in a group, and v2) yes/no whether, for a given row, there is a previous row in the group with a different value for cond (v2=no when group=C and order=1 or 2 but v2=yes when group=C and order=3). I know I can use dplyr to arrange the groups:
x %>% group_by(group) %>% arrange(order, .by_group=T)
but I don't know where to go from there since lag() and lead() are only for the row immediately before or after.