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

如何在R中按多条件生成独立频次表并导出至桌面

解决方案:按院校类型+学位生成独立频次表并导出

前提说明

假设你的数据框df中:

  • 有区分国内/国际院校的字段(示例用institution_type,请替换为你实际的列名,比如通过院校所在国家/地区判断)
  • college_first_degree_0字段包含学位名称(如Associates、Bachelor of Science等)

步骤1:数据预处理(统一学位分类)

先把原始学位归类为你需要的三类,同时筛选德州院校数据:

library(dplyr)

df_processed <- df %>%
  filter(college_state_0 == "Texas") %>%
  mutate(
    # 统一学位分类,适配不同学位表述
    degree_category = case_when(
      grepl("Associate", college_first_degree_0, ignore.case = TRUE) ~ "副学士",
      grepl("Bachelor", college_first_degree_0, ignore.case = TRUE) ~ "学士",
      grepl("Graduate|Master|Doctor", college_first_degree_0, ignore.case = TRUE) ~ "研究生",
      TRUE ~ "其他"
    ),
    # 替换为你实际判断国内/国际的逻辑,比如用院校所在国家列
    institution_type = ifelse(your_domestic_flag_column, "国内毕业生", "国际毕业生")
  ) %>%
  filter(degree_category != "其他") # 过滤未归类的学位

步骤2:生成独立频次表

拆分数据为「院校类型+学位」的分组,对每个分组生成频次表:

# 按院校类型和学位拆分数据
data_groups <- df_processed %>%
  group_split(institution_type, degree_category, .keep = TRUE)

# 定义生成频次表的函数
generate_freq_table <- function(sub_df) {
  type <- unique(sub_df$institution_type)
  degree <- unique(sub_df$degree_category)
  total_n <- nrow(sub_df)
  
  # 生成带百分比的频次表,按计数降序排列
  freq_tbl <- sub_df %>%
    count(college_name_0, name = "Count") %>%
    mutate(`%` = round((Count / total_n) * 100, 1)) %>%
    arrange(desc(Count)) %>%
    rename(Institution = college_name_0)
  
  list(title = paste0(type, "-", degree, "(n=", total_n, ")"), table = freq_tbl)
}

# 批量生成所有分组的频次表
all_tables <- lapply(data_groups, generate_freq_table)

步骤3:导出到桌面

提供两种导出方式,按需选择:

方式1:导出为独立Excel文件

每个分组对应一个Excel文件,直接保存到桌面:

library(writexl)

# 自动识别Windows/Mac桌面路径
desktop_path <- ifelse(Sys.info()["sysname"] == "Windows",
                       file.path(Sys.getenv("USERPROFILE"), "Desktop"),
                       file.path(Sys.getenv("HOME"), "Desktop"))

# 循环导出每个表格
for (tbl in all_tables) {
  # 生成合规文件名,替换特殊字符
  filename <- gsub("[^\\w\\u4e00-\\u9fa5]", "_", tbl$title) %>% paste0(".xlsx")
  write_xlsx(tbl$table, path = file.path(desktop_path, filename))
}

方式2:导出为汇总HTML文件

生成与你示例格式一致的HTML文件,包含所有表格:

library(knitr)

# 拼接HTML内容
html_content <- lapply(all_tables, function(tbl) {
  paste0(
    "<h3>", tbl$title, "</h3>",
    kable(tbl$table, format = "html", table.attr = 'class="s-table"')
  )
}) %>% paste(collapse = "\n")

# 导出到桌面
writeLines(html_content, con = file.path(desktop_path, "学位频次表汇总.html"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 09:30:38