Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flag run-length of grouped intervals

I have a dataframe grouped by grp:

df <- data.frame(
  v = rnorm(25),
  grp = c(rep("A",10), rep("B",15)),
  size = 2)

I want to flag the run-length of intervals determined by size. For example, for grp == "A", size is 2, and the number of rows is 10. So the interval should have length 10/2 = 5. This code, however, creates intervals with length 2:

df %>%
  group_by(grp) %>%
  mutate(
    interval = (row_number() -1) %/% size)
# A tibble: 25 × 4
# Groups:   grp [2]
        v grp    size interval
    <dbl> <chr> <dbl>    <dbl>
 1 -0.166 A         2        0
 2 -1.12  A         2        0
 3  0.941 A         2        1
 4 -0.913 A         2        1
 5  0.486 A         2        2
 6 -1.80  A         2        2
 7 -0.370 A         2        3
 8 -0.209 A         2        3
 9 -0.661 A         2        4
10 -0.177 A         2        4
# … with 15 more rows

How can I flag the correct run-length of the size-determined intervals? The desired output is this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# A tibble: 25 × 4
# Groups:   grp [2]
        v grp    size interval
    <dbl> <chr> <dbl>    <dbl>
 1 -0.166 A         2        0
 2 -1.12  A         2        0
 3  0.941 A         2        0
 4 -0.913 A         2        0
 5  0.486 A         2        0
 6 -1.80  A         2        1
 7 -0.370 A         2        1
 8 -0.209 A         2        1
 9 -0.661 A         2        1
10 -0.177 A         2        1
# … with 15 more rows

>Solution :

If I interpreted your question correctly, this small change should do the trick?

df %>%
  group_by(grp) %>%
  mutate(
    interval = (row_number() -1) %/% (n()/size))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading