有没有更好的方法在NA存在的情况下引入运行-length id?

Is there a better way to introduce run-length id in the presence of NA?

我有这个数据:

df <- data.frame(
  Sequ = c(NA, 8, 8, NA, 1, 1, 1, NA, NA, NA, 22, 22, NA),
  Q = c(NA, "q_x", "", NA, "q_2", "", "", NA, NA, NA, "q_xyz", "", NA)
)

我想做的是在 Sequ 中引入一个正确的 运行-length id 而不是 NA。到目前为止我所尝试的确实得到了我想要的结果,但我的感觉是必须有更好更高效、更简洁的方法:

cats = c("q_x", "q_2", "q_xyz")
df %>%
  mutate(Sequ = cumsum(Q %in% cats)) %>% 
  mutate(Sequ = ifelse(is.na(Q), NA, Sequ))
   Sequ     Q
1    NA  <NA>
2     1   q_x
3     1      
4    NA  <NA>
5     2   q_2
6     2      
7     2      
8    NA  <NA>
9    NA  <NA>
10   NA  <NA>
11    3 q_xyz
12    3      
13   NA  <NA>

有什么帮助吗?

另一种可能的解决方案,

library(dplyr)

df %>% 
 mutate(Sequ = replace(Sequ, !is.na(Sequ), cumsum(grepl('q', Q))[!is.na(Sequ)]))

   Sequ     Q
1    NA  <NA>
2     1   q_x
3     1      
4    NA  <NA>
5     2   q_2
6     2      
7     2      
8    NA  <NA>
9    NA  <NA>
10   NA  <NA>
11    3 q_xyz
12    3      
13   NA  <NA>