boshek
boshek

Reputation: 4406

Count consecutive instances of a certain value

What would be the best dplyr-esque way to answer this question of dat:

How many consecutive times by grp has x been 1 (assuming some internal order to dat)?

EDIT: assume that these ordered and everything should be based on the "last" value in the grp. So that is when order is 4.

library(dplyr)
dat <- data.frame(
  order = c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4),
  x = c(1, 1, 1, 0.5, 1, 1, 1, 1, 1, 0.5, 0.5, 1),
  grp = c(rep("gr1", 4), rep("grp2", 4), rep("grp3", 4))
)
dat
#>    order   x  grp
#> 1      1 1.0  gr1
#> 2      2 1.0  gr1
#> 3      3 1.0  gr1
#> 4      4 0.5  gr1
#> 5      1 1.0 grp2
#> 6      2 1.0 grp2
#> 7      3 1.0 grp2
#> 8      4 1.0 grp2
#> 9      1 1.0 grp3
#> 10     2 0.5 grp3
#> 11     3 0.5 grp3
#> 12     4 1.0 grp3

Desired output:

#>   x  grp
#> 1 0 grp1
#> 2 4 grp2
#> 3 1 grp3

Upvotes: 1

Views: 67

Answers (1)

akrun
akrun

Reputation: 886938

We may do

library(data.table)
setDT(dat)[, .(x = last(rle(x == 1)$lengths) *(last(x) == 1)), grp]
      grp     x
   <char> <int>
1:   grp1     0
2:   grp2     4
3:   grp3     1

Upvotes: 1

Related Questions