使用gt()在R中的上表中进行小计和总计

hec6srdp  于 2023-05-04  发布在  其他
关注(0)|答案(1)|浏览(168)

如你所知,R对列的操作非常好。然而,行可能很困难。另一方面,Excel行很好,尤其是小计。为了解决我的问题,我需要在R表中实现Excel样式。
重要的是小计和总计。表子组上方的小计和第一个子组上方的总计。是否可以从gt() reference中改编代码,将分类汇总放在组上方,而不是tab_row_group中的ALL显示标签,并格式化整个汇总行。本例全部遗漏。谢谢

library(gt)

countrypops |>
  dplyr::filter(
    country_code_2 %in% c("BR", "RU", "IN", "CN", "FR", "DE", "IT", "GB")
  ) |>
  dplyr::filter(year %% 10 == 0) |>
  dplyr::select(country_name, year, population) |>
  tidyr::pivot_wider(names_from = year, values_from = population) |>
  gt(rowname_col = "country_name") |>
  tab_row_group(
    label = md("*BRIC*"),
    rows = c("Brazil", "Russian Federation", "India", "China"),
    id = "bric"
  ) |>
  tab_row_group(
    label = md("*Big Four*"),
    rows = c("France", "Germany", "Italy", "United Kingdom"),
    id = "big4"
  ) |>
  row_group_order(groups = c("bric", "big4")) |>
  tab_spanner(columns = everything(), label = "Year") |>
  fmt_number(n_sigfig = 3, suffixing = TRUE) |>
  summary_rows(
    fns =  list(label = md("**ALL**"), id = "totals", fn = "sum"),
    fmt = ~ fmt_number(., n_sigfig = 3, suffixing = TRUE),
    side = "top"
  ) |>
  tab_style(
    locations = cells_summary(),
    style = cell_fill(color = "lightblue" |> adjust_luminance(steps = +1))
  )
mrfwxfqh

mrfwxfqh1#

我不确定你在找什么,但这很接近吗?

library(gt)

countrypops |>
  dplyr::filter(
    country_code_2 %in% c("BR", "RU", "IN", "CN", "FR", "DE", "IT", "GB")
  ) |>
  dplyr::filter(year %% 10 == 0) |>
  dplyr::select(country_name, year, population) |>
  tidyr::pivot_wider(names_from = year, values_from = population) |>
  gt(rowname_col = "country_name") |>
  tab_row_group(
    label = md("*BRIC*"),
    rows = c("Brazil", "Russian Federation", "India", "China"),
    id = "bric"
  ) |>
  tab_row_group(
    label = md("*Big Four*"),
    rows = c("France", "Germany", "Italy", "United Kingdom"),
    id = "big4"
  ) |>
  row_group_order(groups = c("bric", "big4")) |>
  tab_spanner(columns = everything(), label = "Year") |>
  fmt_number(n_sigfig = 3, suffixing = TRUE) |>
  summary_rows(
    fns =  list(label = md("Subgroup Total"), id = "totals", fn = "sum"),
    fmt = ~ fmt_number(., n_sigfig = 3, suffixing = TRUE),
    side = "top"
  ) |>
  tab_style(
    locations = cells_summary(),
    style = cell_fill(color = "lightblue" |> adjust_luminance(steps = +1))
  ) |>
  grand_summary_rows(
    columns = c('1960', '1970', '1980', '1990', '2000', '2010', '2020'),
    fns = list(
      'Grand Total' ~ sum(.)
    ),
    , 
    side = 'top',
    fmt = ~ fmt_number(., decimals = 0, use_seps = FALSE)
  )

相关问题