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

group sequential numbers in sets using R

Can anyone point me to a way to group pairs of numbers into sets. For e.g.

   g a set
1  a 1 1
2  a 2 1
3  b 1 1
4  b 2 1
5  c 1 1
6  c 2 1
7  c 3 2
8  c 4 2
9  d 1 1
10 d 2 1
11 e 1 1
12 e 2 1
13 e 3 2
14 e 4 2
15 e 5 3
16 e 6 3

Here each group, g, has a counter, a. In a, 1 and 2 are set 1, 3 and 4 are set 2, 5 and 6 are set 3 and so. Is there a way top formalise the calculation of set as a increases to any number? If so what tools in R would facilitate this?

I have tried using cumsum with dply:group_by() but this is clearly incorrect

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

df <- df %>% group_by(g) %>% mutate(set = cumsum(a))

   g         a   set
   <chr> <dbl> <dbl>
 1 a         1     1
 2 a         2     3
 3 b         1     1
 4 b         2     3
 5 c         1     1
 6 c         2     3
 7 c         3     6
 8 c         4    10
 9 d         1     1
10 d         2     3
11 e         1     1
12 e         2     3
13 e         3     6
14 e         4    10
15 e         5    15
16 e         6    21

>Solution :

I think you can just use some modular arithmetic here. Subtract 1 from a and find the integer part after dividing by 2. Add 1 to this to get your result.

df %>% mutate(set = (a - 1) %/% 2 + 1)
#>    g a set
#> 1  a 1   1
#> 2  a 2   1
#> 3  b 1   1
#> 4  b 2   1
#> 5  c 1   1
#> 6  c 2   1
#> 7  c 3   2
#> 8  c 4   2
#> 9  d 1   1
#> 10 d 2   1
#> 11 e 1   1
#> 12 e 2   1
#> 13 e 3   2
#> 14 e 4   2
#> 15 e 5   3
#> 16 e 6   3

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