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

在RShiny中绘制Assurance Curve报错:参数长度为零求助

解决RShiny中绘制Assurance Curve出现的“argument is of length zero”错误

可能的原因及对应修复方案

1. 输入控件未初始化导致值为空

Shiny应用启动时,部分输入控件可能未赋予初始值,导致input$pt_baynor、input$select6等参数为空,触发if判断后执行代码时,传递给assurance_nd_na的参数长度为0。

修复:

  • 给所有输入控件设置value初始值,比如numericInput("n_a", label = "n_a", value = 50),确保启动时参数不为空。
  • 在代码开头添加非空检查,用req()函数暂停空参数下的代码执行:
req(input$n_a, input$n_d, input$theta_0, input$theta_1, input$sig1, input$alpha, input$select6, input$pt_baynor)

2. assurance_nd_na返回的assurance_table为空

部分输入组合下,assurance_nd_na可能无法生成有效的assurance_table,导致tbl为空,ggplot无法绘制图形。

修复:

  • 获取tbl后添加非空检查:
ass_vals = assurance_nd_na(...)
tbl = ass_vals$assurance_table
req(tbl, msg = "无法生成有效的Assurance数据")
  • 先在普通R脚本中用Shiny输入的初始值测试assurance_nd_na,确认能返回正常的assurance_table。

3. ggplot的aes映射写法不稳健

使用tbl[,1]和tbl[,2]的索引方式,若tbl列名变化或为空,会直接导致长度0的错误。建议改用列名映射。

修复:
先通过colnames(tbl)确认assurance_table的列名,假设第一列是样本量(列名n)、第二列是Assurance值(列名assurance),修改aes部分:

p2 = ggplot(data = tbl, aes(x = n, y = assurance, color = "red"))+

4. 多余的plot(p2)调用

在Shiny的renderPlot中,直接返回ggplot对象即可,无需调用plot(p2),该操作可能引发额外错误。

修复:
删除plot(p2),直接在代码末尾返回p2。

修复后的完整代码示例

output$plot2 = renderPlot({
    req(input$n_a, input$n_d, input$theta_0, input$theta_1, input$sig1, input$alpha, input$select6, input$pt_baynor)
    
    n = seq(10,250,5)
    n_a = input$n_a
    n_d = input$n_d
    the_0 = input$theta_0
    the_1 = input$theta_1
    sig1 = input$sig1
    alpha = input$alpha
    
    if(input$pt_baynor > 0){
      ass_vals = assurance_nd_na(n = n, n_a = n_a, n_d = n_d, theta_0 = the_0, theta_1 = the_1, sigsq = sig1, alt = input$select6, alpha = alpha)
      tbl = ass_vals$assurance_table
      req(tbl, msg = "无法生成有效的Assurance数据")
      
      # 替换为实际列名,需提前确认assurance_table的列名
      p2 = ggplot(data = tbl, aes(x = n, y = assurance, color = "red"))+
        geom_point(size = 3)+
        geom_line(lwd = 1.2)+
        labs(title = "Assurance Curve",
             x = "Sample Size n",
             y = "Assurance")+
        theme(legend.position = "none",
              axis.text = element_text(size = 20),
              axis.title = element_text(size = 24),
              plot.title = element_text(size = 28))
      p2
    } else{
      # 条件不满足时返回提示空图
      ggplot() + geom_text(aes(x=1,y=1), label="请调整参数以生成曲线") + theme_void()
    }
  })

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:53:11