You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言使用gt包按category循环生成type分组表格并动态命名的方法

实现方案

你可以通过遍历category的唯一取值,动态生成标题和导出文件名即可,以下是完整可运行代码:

# 加载依赖包
library(gt)
library(magrittr)
library(dplyr)
library(tools)

# 示例数据
df <- structure(list(category = c("food", "food", "food", "food", "electronic product", 
"electronic product", "electronic product", "electronic product"
), type = c("vegetable", "vegetable", "fruit", "fruit", "computer", 
"computer", "other", "other"), variable = c("cabbage", "radish", 
"apple", "pear", "monitor", "mouse", "camera", "calculator"), 
    price = c(6, 5, 3, 2.9, 2000, 10, 600, 35), quantity = c(2L, 
    4L, 5L, 10L, 1L, 3L, NA, 1L)), class = "data.frame", row.names = c(NA, 
-8L))

# 提取所有唯一的category取值
cat_list <- unique(df$category)

# 遍历每个类别生成对应表格
for (current_cat in cat_list) {
  current_dt <- df %>% 
    filter(category == current_cat) %>% 
    group_by(type) %>%
    gt() %>% 
    # 动态生成标题,toTitleCase可实现首字母大写,和你示例的Food格式匹配
    tab_header(
      title = md(toTitleCase(current_cat))
    ) %>%
    fmt_missing(
      columns = where(is.numeric),
      missing_text = "-"
    ) %>%
    tab_style(
      locations = cells_column_labels(columns = everything()),
      style     = list(
        cell_borders(sides = "bottom", weight = px(3)),
        cell_text(weight = "bold")
      )
    ) %>%
    tab_style(
      locations = cells_row_groups(groups = everything()),
      style     = list(
        cell_text(weight = "bold")
      )
    ) %>%
    cols_align(align = "center", columns = where(is.character)) %>%
    cols_align(align = "right", columns = where(is.numeric))
  
  # 动态生成文件名,将类别名中的空格替换为下划线,避免路径识别问题
  file_name <- paste0(gsub(" ", "_", current_cat), ".png")
  # 导出当前类别的表格
  gt::gtsave(current_dt, file = file.path("./", file_name))
}

可选调整说明

  • 如果不需要标题首字母大写,直接把toTitleCase(current_cat)替换为current_cat即可
  • 如果可以接受文件名带空格,直接去掉gsub逻辑,用paste0(current_cat, ".png")生成文件名即可

内容的提问来源于stack exchange,提问作者ah bon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 23:54:02