Skip to contents

Why this package exists

g6tr.cohorts is an infrastructure package.

Its main purpose is to formalize subgroup definitions as explicit objects that contain:

  • respondent IDs (id)
  • subgroup weights (weight)

This makes subgroup logic reusable and less error-prone across other packages that compute by-subgroup summaries (means, rates, model outputs, etc.).

Core objects

us_cohort <- 
  example_data |>
  filter(country == "US") |>
  create_cohort(
    id_col = response_id,
    weight_col = weight
  )

us_cohort
#> Cohort (N = 190)
#> # A tibble: 190 × 2
#>    id    weight
#>    <chr>  <dbl>
#>  1 R0001  1.48 
#>  2 R0003  1.16 
#>  3 R0005  0.639
#>  4 R0006  1.05 
#>  5 R0007  0.926
#>  6 R0011  0.665
#>  7 R0016  0.752
#>  8 R0023  1.16 
#>  9 R0024  0.660
#> 10 R0028  1.06 
#> # ℹ 180 more rows

A cohort is just a data frame with id and weight and class "cohort".

class(us_cohort)
#> [1] "cohort"     "tbl_df"     "tbl"        "data.frame"

Cohort sets

create_cohort_set() builds many cohorts at once from grouping columns.

cohorts <- 
  example_data |>
  create_cohort_set(
    id_col = response_id,
    grp_cols = c(country, customer),
    population = TRUE,
    weight_col = weight
  )

cohorts
#> Cohort Set
#> # A tibble: 7 × 6
#>   column     label                level      cohort                 n weighted_n
#>   <chr>      <chr>                <chr>      <list>             <int>      <dbl>
#> 1 population Overall population   population <cohort [500 × 2]>   500      503. 
#> 2 country    Country of residence France     <cohort [50 × 2]>     50       54.0
#> 3 country    Country of residence Germany    <cohort [100 × 2]>   100       95.4
#> 4 country    Country of residence UK         <cohort [160 × 2]>   160      165. 
#> 5 country    Country of residence US         <cohort [190 × 2]>   190      189. 
#> 6 customer   Customer status      No         <cohort [188 × 2]>   188      188. 
#> 7 customer   Customer status      Yes        <cohort [312 × 2]>   312      315.

Validation helpers

check_cohort() and check_cohort_set() are lightweight validators you can run at package boundaries before downstream computations.

How this supports downstream summaries

A typical pattern in another package is:

  1. Receive a cohort or cohort_set object.
  2. Join respondent-level analysis data using id.
  3. Compute weighted subgroup summaries using weight.

Minimal example:

weighted_mean_for_cohort <- function(data, cohort, value_col) {
  data |>
    select(response_id, all_of(value_col)) |>
    inner_join(cohort, by = c("response_id" = "id")) |>
    summarise(
      estimate = weighted.mean(.data[[value_col]], .data$weight, na.rm = TRUE)
    ) |>
    pull(estimate)
}

weighted_mean_for_cohort(
  data = example_data |>
    mutate(customer_num = if_else(customer == "Yes", 1, 0)),
  cohort = us_cohort,
  value_col = "customer_num"
)
#> [1] 0.6381239