Q:

dplyr lag across groups

I am trying to do something like a lag, but across and not within groups.  Sample data:
df <- data.frame(flag = c("A", "B", "A", "B", "B", "B", "A", "B", "B", "A", "B"),
                 var = c("AB123","AC124", "AD125", "AE126",
                          "AF127", "AG128", "AF129",
                          "AG130","AH131",
                          "AHI132", "AJ133"))
)

The goal for every flag="B" is to create lagvar with the previous var value where flag="A".
This will show the desired output:
df1 <- data.frame(flag = c("A", "B", "A", "B", "B", "B", "A", "B", "B", "A", "B"),
                 var = c("AB123","AC124", "AD125", "AE126",
                          "AF127", "AG128", "AF129",
                          "AG130","AH131",
                          "AHI132", "AJ133"),
                 lagvar = c("","AB123","","AD125","AD125","AD125","","AF129","AF129","","AHI132")
)

A dplyr solution is preferred, but I'm not picky!
EDIT:  I found a solution using the zoo package but am interested if others have better ideas.  df$lagvar <- ifelse(df$flag == "A", df$var, NA)
df <- df %>% 
        mutate(lagvar = na.locf(lagvar)

A:

Here you go. I used NA instead of blanks, but you can adjust as needed:
df %>% mutate(lagvar = ifelse(flag == "A", as.character(var), NA),
              lagvar = zoo::na.locf(lagvar),
              lagvar = ifelse(flag == "A", NA, lagvar))
#    flag    var lagvar
# 1     A  AB123   <NA>
# 2     B  AC124  AB123
# 3     A  AD125   <NA>
# 4     B  AE126  AD125
# 5     B  AF127  AD125
# 6     B  AG128  AD125
# 7     A  AF129   <NA>
# 8     B  AG130  AF129
# 9     B  AH131  AF129
# 10    A AHI132   <NA>
# 11    B  AJ133 AHI132

