assigning group indices within multiple layers of groupings

Hi. I am trying to assign a unique treatment ID within layers of multiple groupings.
Example data I'm starting with is as follows:

library(dplyr)

dat <- tibble(year = c(rep(2016, 8), rep(2017, 4)),
              site = c( rep("A", 6), rep("B", 2), rep("A", 4)),
              crop = c(rep("corn", 6), rep("soy", 6)),
              trt = c("HI", "HI", "MED", "MED", "LO", "LO", "0N", "0N", "none", "none", "TILL", "TILL"),
              rep = c(rep(1:2, 6)))
dat

I want each year, site, and crop combination to have a unique 'trt_ID' assigned to each unique trt WITHIN those combinations.

I've tried using group by and group_indices, and also creating a dummy variable to group by.

dat %>%
  group_by(year, site, crop) %>%
  mutate(group_id = group_indices(., trt))


dat %>%
unite(year, site, crop, col = "thing_id") %>%
  mutate(group_id = group_indices(., thing_id))

Neither produce my desired results:

desireddat <- tibble(year = c(rep(2016, 8), rep(2017, 4)),
                     site = c( rep("A", 6), rep("B", 2), rep("A", 4)),
                     crop = c(rep("corn", 6), rep("soy", 6)),
                     trt = c("HI", "HI", "MED", "MED", "LO", "LO", "0N", "0N", "none", "none", "TILL", "TILL"),
                     rep = c(rep(1:2, 6)),
                     
                     trt_id = c(1, 1, 2, 2, 3, 3, 1, 1, 1, 1, 2, 2))

I've found some solutions online, but couldn't find any that use multiple layers of groupings and the tidyverse functions. Any help is much appreciated!

this should come very close to what you are looking for. only the order of indices within groups is not as in your desired outcome. guess it requires some finetuning with sort or factor levels.

dat %>% 
  group_by(year, site, crop) %>% 
  group_map(~mutate(.,index=group_indices(.,trt)))
#> # A tibble: 12 x 6
#> # Groups:   year, site, crop [3]
#>     year site  crop  trt     rep index
#>    <dbl> <chr> <chr> <chr> <int> <int>
#>  1  2016 A     corn  HI        1     1
#>  2  2016 A     corn  HI        2     1
#>  3  2016 A     corn  MED       1     3
#>  4  2016 A     corn  MED       2     3
#>  5  2016 A     corn  LO        1     2
#>  6  2016 A     corn  LO        2     2
#>  7  2016 B     soy   0N        1     1
#>  8  2016 B     soy   0N        2     1
#>  9  2017 A     soy   none      1     1
#> 10  2017 A     soy   none      2     1
#> 11  2017 A     soy   TILL      1     2
#> 12  2017 A     soy   TILL      2     2

group_map...that's a new and fun one. Thanks zoowalk, this is great.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.