The fmt_bins() function

Use the countrypops dataset to create a gt table. Before even getting to the gt() call, we use cut() in conjunction with scales::breaks_log() to create some highly customized bins. Consequently each country’s population in the 2021 year is assigned to a bin. These bins have a characteristic type of formatting that can be used as input to fmt_bins(), and using that formatting function allows us to customize the presentation of those ranges. For instance, here we are formatting the left and right values of the ranges with fmt_integer() (using formula syntax).

countrypops |>
  dplyr::filter(year == 2021) |>
  dplyr::select(country_code_2, population) |>
  dplyr::mutate(population_class = cut(
    population,
    breaks = scales::breaks_log(n = 20)(population)
    )
  ) |>
  dplyr::group_by(population_class) |>
  dplyr::summarize(
    count = dplyr::n(),
    countries = paste0(country_code_2, collapse = ",")
  ) |>
  dplyr::arrange(desc(population_class)) |>
  gt() |>
  fmt_flag(columns = countries) |>
  fmt_bins(
    columns = population_class,
    fmt = ~ fmt_integer(., suffixing = TRUE)
  ) |>
  cols_label(
    population_class = "Population Range",
    count = "",
    countries = "Countries"
  ) |>
  cols_width(
    population_class ~ px(150),
    count ~ px(50)
  ) |>
  tab_style(
    style = cell_text(style = "italic"),
    locations = cells_body(columns = count)
  )
Population Range Countries
1B–2B 2
300M–500M 1
200M–300M 4
100M–200M 7
50M–100M 15
30M–50M 20
20M–30M 11
10M–20M 31
5M–10M 32
3M–5M 12
2M–3M 14
1M–2M 10
500K–1M 12
300K–500K 6
200K–300K 4
100K–200K 10
50K–100K 9
30K–50K 12
10K–20K 3