0

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

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

1 Answers1

1

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

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87