Filter groups that are not consecutively numbered

Viewed 27

I have a dataframe with a grouping variable Sequ and a counting variable grp:

df <- data.frame(
  Sequ = c(1,1,2,2,2,2,3,3,3,4,4,4,4),
  grp = c(1,2,
          1,3,4,5,
          1,2,3,
          1,2,4,5)
)

I need to filter those Sequences where the grpcount is not by increments of 1 but greater than 1. The following method identifies the rows where the 'break' occurs but it does not filter the Sequences in their entirety:

df %>%
  group_by(Sequ) %>%
  filter(lead(grp) - grp > 1)
# A tibble: 2 × 2
# Groups:   Sequ [2]
   Sequ   grp
  <dbl> <dbl>
1     2     1
2     4     2

How can I get this desired output:

df
   Sequ grp
1     2   1
2     2   3
3     2   4
4     2   5
5     4   1
6     4   2
7     4   4
8     4   5
1 Answers

You may try

library(dplyr)

df %>%
  group_by(Sequ) %>%
  filter(!all(abs(diff(grp)) == 1))
   Sequ   grp
  <dbl> <dbl>
1     2     1
2     2     3
3     2     4
4     2     5
5     4     1
6     4     2
7     4     4
8     4     5
Related