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

在R语言中创建基于医保计划的条件/动态表格

问题描述

我有一个约40行40列的Excel表格,每行对应一个医保计划,需要向这些计划发送分析结果。表格的CSV结构如下:

id <- c("3235453", "321354365", "21354315", "32135135", "2121421", "123123123", "123123123", "123123123", "12312234", "234234234", "234234234", "3453453", "345345345", "2154651", "345345345", "34534534", "345345345", "345345345", "77878978", "234234234234")
Plan_name<- c("angers", "strasbourg",  "Benzema", "angers", "montpellier", "Arsenal",  "rouen", "limoges", "CHG", "brest", "stanne", "aphp_psl", "stanne",      "strasbourg",  "clairval", "stanne", "stanne", "caen", "Ventura", "brest")
Section.C<- c("X", "", "", "", "X", "X", "", "", "X", "", "", "", "", "", "", "", "", "", "", "X")
Section.B<-c("", "X", "", "X", "", "", "X", "", "", "", "", "", "", "", "", "", "", "", "X", "X")
Section.D<-c("", "", "", "", "", "", "", "", "X", "", "X", "", "", "X", "", "", "", "", "X", "X")
df1 <- data.frame (id, Plan_name, Section.B, Section.C, Section.D)

我已经完成了部分结果提取步骤,但不知道如何生成依赖该Excel表的目标表格。目前编写的代码如下:

---
# in YAML
params:
  plan: "Ventura"
---

df = read.xlsx("MailMerge_2020.xlsx", sheet = 1)
t2 = df %>% filter(Plan-name == params$plan) %>% 
select(Section.B, Section.C, Section.D) %>% 
select_if(~ !any(is.na(.)))

需要将结果转换为符合指定样式的表格(仅显示该计划有结果的Section行)。


解决方案

步骤1:修正代码并转换数据格式

首先修正现有代码的变量名错误(Plan-name应为Plan_name),然后将宽格式数据转为长格式,筛选出有结果(值为"X")的Section:

library(tidyverse)
library(readxl)

# 读取Excel数据
df <- read_xlsx("MailMerge_2020.xlsx", sheet = 1)

# 处理指定医保计划的数据
target_plan <- params$plan
cleaned_data <- df %>%
  filter(Plan_name == target_plan) %>%
  select(Section.B, Section.C, Section.D) %>%
  # 转长格式,方便筛选有结果的项
  pivot_longer(cols = everything(), names_to = "Section", values_to = "Result") %>%
  # 筛选出有结果的行(假设"X"代表有结果)
  filter(Result == "X") %>%
  select(Section)

步骤2:生成目标样式表格

根据需求,推荐两种在R Markdown中生成表格的方式:

方式1:使用knitr::kable快速生成

library(knitr)

cleaned_data %>%
  kable(col.names = c("有结果的Section"),
        caption = paste0("医保计划 ", target_plan, " 分析结果"),
        align = "c") %>%
  kable_styling(full_width = FALSE, position = "left")

方式2:使用gt包自定义样式(更灵活)

library(gt)

cleaned_data %>%
  gt() %>%
  cols_label(Section = "有结果的Section") %>%
  tab_header(title = paste0("医保计划 ", target_plan, " 分析结果")) %>%
  tab_options(table.width = pct(50),
              table.align = "left")

关键说明

  • 如果你的"有结果"定义不是值为"X",而是非空/非NA,可将filter(Result == "X")替换为filter(Result != "" & !is.na(Result))
  • 参数化报告中,params$plan会自动传递当前要生成的计划名称,实现批量生成不同计划的分析表格

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 04:20:35