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

R Shiny报错arguments imply differing number of rows: 0, 1 如何解决

问题排查与解决方案

报错根本原因

你手动测试时传入的是完整赋值的input列表,而Shiny应用初始化阶段,所有输入组件的数值还未完成加载,input对象内的字段全部为NULL,此时renderPlotly会触发第一次执行:

  • pred_prob_func接收到的入参input中所有字段为空,生成的预测数据集行数为0
  • 预测逻辑尝试返回长度为1的结果,就会触发「行数不匹配」的报错

修复方案

方案1:添加必填输入校验(最推荐)

在renderPlotly代码开头加入req()函数校验所有必填输入,只有所有输入都有有效值时才执行后续渲染逻辑:

output$int_plot <- renderPlotly({
  # 新增:校验所有必填输入项均已赋值,无有效值时直接终止后续执行
  req(
    input$Age, input$Gender, input$GCS_Bestin24, input$Premorbid_depression,
    input$Antidep_first6m, input$MIP_1a, input$MIP_3a, input$RANTES,
    input$sIL_6R, input$ITAC, input$IL_21, input$Fractalkine, input$TNF_a,
    input$IL_1b, input$IL_7, input$IL_10, input$GM_CSF, input$MIP_1b,
    input$thresholdslider
  )

  # 原有代码不变
  phats_graph$`Total Percentile` <- unlist(t(sapply(phats_graph$Phat, function(x) quantile_fun(value=x)))[,1])
  phats_graph$`PTD Percentile` <- unlist(t(sapply(phats_graph$Phat, function(x) quantile_fun(value=x)))[,2])
  phats_graph$`No PTD Percentile` <- unlist(t(sapply(phats_graph$Phat, function(x) quantile_fun(value=x)))[,3])

  int_plot <- ggplot(phats_graph, aes(ptd_per=`No PTD Percentile`)) + geom_density(aes(x=Phat, fill = `PTD Event Status`), alpha=0.5) +
    geom_vline(xintercept = input$thresholdslider, linetype = 'dashed') +
    geom_vline(xintercept = pred_prob_func(input)$pred_prob) +
    xlab('Threshold Percentage') + ylab('Density') +
    theme_minimal() + scale_fill_manual(values=c("#5D3A9B", "#E66100"), name="")

  ggplotly(int_plot, tooltip=c("x", "ptd_per"))
})

方案2:给输入组件设置默认值

在UI定义部分,给所有输入控件(numericInput/sliderInput/selectInput等)设置初始value,确保应用启动时input就有有效值,不会触发空值调用。

方案3:函数内部添加空值防护

也可以在pred_prob_func内部增加空值判断逻辑,输入不完整时直接返回默认值:

pred_prob_func <- function(input){
  # 新增空值校验
  required_fields <- c("Age", "Gender", "GCS_Bestin24", "Premorbid_depression", "Antidep_first6m",
                       "MIP_1a", "MIP_3a", "RANTES", "sIL_6R", "ITAC", "IL_21", "Fractalkine",
                       "TNF_a", "IL_1b", "IL_7", "IL_10", "GM_CSF", "MIP_1b", "thresholdslider")
  if (any(sapply(required_fields, function(f) is.null(input[[f]])))) {
    return(list(pred_prob = 0.5, classification = "No Event"))
  }
  # 原有逻辑不变
  pred_prob = predict(final_model, test.data.function(input), type="prob")[,"PTD"]
  classification <- ifelse(pred_prob >= input$thresholdslider, "PTD Event", "No Event")
  return(list(pred_prob=pred_prob, classification=classification))
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 04:36:06