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

R Flexdashboard中通过selectInput切换带格式表格的实现问题

解决Flexdashboard中切换带样式表格的问题

我来帮你搞定这个表格切换的需求!你之前用renderTable()的方式没法保留kableExtra设置的样式,核心原因是renderTable()只能生成基础HTML表格,不支持自定义的样式渲染。咱们换成renderUI() + uiOutput()的组合,就能完美保留你想要的所有表格格式啦。

完整代码示例

---
title: "切换带样式表格"
output: flexdashboard::flex_dashboard
runtime: shiny
---

```{r setup, include=FALSE}
library(flexdashboard)
library(DT)
knitr::opts_chunk$set(echo = TRUE)
library(ggplot2)
library(png)
library(grid)
library(kableExtra)
library(knitr)
library(dplyr)

# 加载你的数据集(替换成实际读取路径)
# MB_Val <- read.csv("MB_Val.csv")
# DS_Val <- read.csv("DS_Val.csv")

Column {data-width=300}

选择平台

selectInput("platform", label = "Select Platform:", choices = c("MB","DS"))

Column {data-width=700}

展示表格

uiOutput("styled_table")

output$styled_table <- renderUI({
  if(input$platform == "MB"){
    table_output <- MB_Val %>% 
      mutate(Val = cell_spec(
        format(round(Val, 2), nsmall = 2),
        "html", color = "white", bold = T, background = "#7FC64F")) %>%
      mutate(ValFm = cell_spec(
        format(round(ValFm, 2), nsmall = 2),
        "html", color = "white", bold = T, background = "#7FC64F")) %>%
      kable("html", escape = F, align = c('l',rep('c',ncol(MB_Val)-1))) %>%
      kable_styling(bootstrap_options = c("striped", "condensed","hover")) %>%
      scroll_box()
  } else {
    table_output <- DS_Val %>% 
      mutate(Val = cell_spec(
        format(round(Val, 2), nsmall = 2),
        "html", color = "white", bold = T, background = "#7FC64F")) %>%
      mutate(ValFm = cell_spec(
        format(round(ValFm, 2), nsmall = 2),
        "html", color = "white", bold = T, background = "#7FC64F")) %>%
      kable("html", escape = F,align = c('l',rep('c',ncol(DS_Val)-1))) %>%
      kable_styling(bootstrap_options = c("striped", "condensed","hover")) %>%
      scroll_box(height = "200px")
  }
  # 输出完整HTML样式的表格
  HTML(table_output)
})
### 关键说明
- 必须在YAML头部加上`runtime: shiny`,让flexdashboard支持Shiny交互组件,这是实现动态切换的基础。
- 用`uiOutput("styled_table")`在页面预留表格位置,再通过`renderUI()`根据选择的平台生成对应样式的表格,最后用`HTML()`输出kableExtra生成的完整HTML内容,这样所有的颜色、加粗、滚动框等样式都能完整保留。
- 别忘了加载`dplyr`包(因为用到了`mutate`函数),如果之前没加载的话一定要补上。

内容的提问来源于stack exchange,提问作者Morts81
相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:54:34