The fmt_fraction() function

Using a summarized version of the pizzaplace dataset, let’s create a gt table. With fmt_fraction() we can format the f_sold and f_income columns to display fractions. As for how the fractions are represented, we are electing to use accuracy = 10. This gives all fractions as tenths. We won’t simplify the fractions (by using simplify = FALSE) and this means that a fraction like 5/10 won’t become 1/2. With layout ="diagonal", we get a diagonal display of all fractions.

pizzaplace |>
  dplyr::group_by(type, size) |>
  dplyr::summarize(
    sold = dplyr::n(),
    income = sum(price),
    .groups = "drop_last"
  ) |>
  dplyr::group_by(type) |>
  dplyr::mutate(
    f_sold = sold / sum(sold),
    f_income = income / sum(income),
  ) |>
  dplyr::arrange(type, dplyr::desc(income)) |>
  gt(rowname_col = "size") |>
  tab_header(
    title = "Pizzas Sold in 2015",
    subtitle = "Fraction of Sell Count and Revenue by Size per Type"
  ) |>
  fmt_integer(columns = sold) |>
  fmt_currency(columns = income) |>
  fmt_fraction(
    columns = starts_with("f_"),
    accuracy = 10,
    simplify = FALSE,
    layout = "diagonal"
  ) |>
  sub_missing(missing_text = "") |>
  tab_spanner(
    label = "Sold",
    columns = contains("sold")
  ) |>
  tab_spanner(
    label = "Revenue",
    columns = contains("income")
  ) |>
  text_transform(
    locations = cells_body(),
    fn = function(x) {
      dplyr::case_when(
        x == 0 ~ "<em>nil</em>",
        x != 0 ~ x
      )
    }
  ) |>
  cols_label(
    sold = "Amount",
    income = "Amount",
    f_sold = md("_f_"),
    f_income = md("_f_")
  ) |>
  cols_align(align = "center", columns = starts_with("f")) |>
  tab_options(
    table.width = px(400),
    row_group.as_column = TRUE
  )
Pizzas Sold in 2015
Fraction of Sell Count and Revenue by Size per Type
Sold
Revenue
Amount f Amount f
chicken L 4,932 410 $102,339.00 510
M 3,894 410 $65,224.50 310
S 2,224 210 $28,356.00 110
classic L 4,057 310 $74,518.50 310
S 6,139 410 $69,870.25 310
M 4,112 310 $60,581.75 310
XL 552 nil $14,076.00 110
XXL 28 nil $1,006.60 nil
supreme L 4,564 410 $94,258.50 510
M 4,046 310 $66,475.00 310
S 3,377 310 $47,463.50 210
veggie L 5,403 510 $104,202.70 510
M 3,583 310 $57,101.00 310
S 2,663 210 $32,386.75 210