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

如何在Shiny中基于if条件为DT::datatable动态添加参数

问题根源

你的代码有两个核心错误:

  • R不支持直接在函数的参数列表内写if条件块来动态传参,你把if(is.null(container_dat)){...}放在datatable()的参数位属于语法错误
  • 原代码中headerCallback对应的JS()调用缺少闭合括号,本身就会触发解析报错

解决方案

我们可以先构造datatable的参数列表,根据container_dat是否为空动态添加container参数,再通过do.call调用datatable即可,不传container参数时datatable会自动使用默认容器,刚好匹配你的需求。修改后的完整代码如下:

table_opt = function(x, edit_y, container_dat = NULL, form_type = "", col_list = NULL){
  DT::renderDataTable({
    ####### Percentage Format
    if(form_type == "%")
    {
      # 先构造基础参数列表
      dt_params <- list(
        data = x,
        editable = edit_y,
        rownames = FALSE,
        options = list(
          paging = FALSE,
          ordering = FALSE,
          searching = FALSE,
          deferRender = TRUE,
          class = "compact",
          headerCallback = DT::JS(
            "function(thead) {",
            "$(thead).css('font-size','14px');",
            "$(thead).css('background-color','#000000');",
            "$(thead).css('color','#ffffff');",
            "}"
          ),
          columnDefs = list(list(className = 'dt-center', targets = '_all'))
        )
      )
      # 动态添加container参数
      if(!is.null(container_dat)){
        dt_params$container <- container_dat
      }
      # 调用datatable并格式化
      do.call(DT::datatable, dt_params) %>%
        DT::formatPercentage(col_list, digits = 2)
    }
    # 可在此处补充其他form_type对应的逻辑,避免非%格式调用时返回空表格
  })
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 20:15:04