3

I have this tibble with 8 groups:

df <- structure(list(group1 = c(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 5, 6, 
6, 7, 8, 8)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-16L))

   group1
    <dbl>
 1      1
 2      1
 3      2
 4      2
 5      3
 6      3
 7      4
 8      4
 9      5
10      5
11      5
12      6
13      6
14      7
15      8
16      8

How can I create a new group2 that combines each consecutive N (let's say N=2) groups to one new group like:

   group1 group2
    <dbl>  <dbl>
 1      1      1
 2      1      1
 3      2      1
 4      2      1
 5      3      2
 6      3      2
 7      4      2
 8      4      2
 9      5      3
10      5      3
11      5      3
12      6      3
13      6      3
14      7      4
15      8      4
16      8      4

Background: If I want to do it with rows I would use

df %>% 
  mutate(Col2 = rep(row_number(), each=2, length.out = n()))

But instead of row_number() I would like to say group.

TarJae
  • 72,363
  • 6
  • 19
  • 66

3 Answers3

4

You could use (group1 + N - 1) %/% N

library(dplyr)

N <- 2
df |> 
  mutate(group = (group1 + N - 1) %/% N)
#> # A tibble: 16 × 2
#>    group1 group
#>     <dbl> <dbl>
#>  1      1     1
#>  2      1     1
#>  3      2     1
#>  4      2     1
#>  5      3     2
#>  6      3     2
#>  7      4     2
#>  8      4     2
#>  9      5     3
#> 10      5     3
#> 11      5     3
#> 12      6     3
#> 13      6     3
#> 14      7     4
#> 15      8     4
#> 16      8     4
stefan
  • 90,330
  • 6
  • 25
  • 51
4

Another option using group_by with cur_group_id like this:

library(dplyr)
df %>%
  group_by(group1) %>%
  mutate(Col2 = (cur_group_id() + 1) %/% 2) 
#> # A tibble: 16 × 2
#> # Groups:   group1 [8]
#>    group1  Col2
#>     <dbl> <dbl>
#>  1      1     1
#>  2      1     1
#>  3      2     1
#>  4      2     1
#>  5      3     2
#>  6      3     2
#>  7      4     2
#>  8      4     2
#>  9      5     3
#> 10      5     3
#> 11      5     3
#> 12      6     3
#> 13      6     3
#> 14      7     4
#> 15      8     4
#> 16      8     4

Created on 2023-03-14 with reprex v2.0.2

Quinten
  • 35,235
  • 5
  • 20
  • 53
2

Try

library(dplyr)
df %>%
    mutate(group2 = ((group1-1) %/% 2) + 1)

-output

# A tibble: 16 × 2
   group1 group2
    <dbl>  <dbl>
 1      1      1
 2      1      1
 3      2      1
 4      2      1
 5      3      2
 6      3      2
 7      4      2
 8      4      2
 9      5      3
10      5      3
11      5      3
12      6      3
13      6      3
14      7      4
15      8      4
16      8      4
akrun
  • 874,273
  • 37
  • 540
  • 662