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!