首页 > 解决方案 > 摆脱 R 控制台中的“参数长度为零”错误消息

问题描述

我有下面的闪亮应用程序,其中显示了 2 个数字输入。该应用程序运行良好,因为当总和不是 40 时会显示错误消息。令人讨厌的,我想摆脱的是错误消息

Warning: Error in if: argument is of length zero

当我第一次运行应用程序时,它出现在 r 控制台中。我知道这来自line 38并且与NULL一开始的价值观有关。有趣的是,当我不使用renderUI()2 个数字输入时,不会显示此错误消息。但我需要他们在我的实际情况下是这样的。

library(shiny)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      #This hides the temporary warning messages while the plots are being created
      tags$style(type="text/css",
                 ".shiny-output-error { visibility: hidden; }",
                 ".shiny-output-error:before { visibility: hidden; }"
      ),
      uiOutput("factors_weight_one_two"),
      htmlOutput('weight_message')
    ),
    mainPanel(

    )
  )
)

server <- function(input, output) {
  output$factors_weight_one_two <- renderUI({
    fluidRow(
      column(6, numericInput(
        "factors_weight_one",
        "Factor 1", 20, 
        min = 1, max = 100,
        width = "90%")),
      column(6, numericInput(
        "factors_weight_two",
        "Factor 2", 20, 
        min = 1, max = 100,
        width = "90%"))
    )
  })
  output$weight_message <- renderText({

      if(!is.null(as.numeric(input$factors_weight_one) + as.numeric(input$factors_weight_two) ) & as.numeric(input$factors_weight_one) + as.numeric(input$factors_weight_two)  != 40){
        sprintf('<font color="%s">%s</font>', 'red', "Your weights don't sum to 40")
      }  else {
        sprintf('<font color="%s">%s</font>', 'red', "")
      }

  })

}

shinyApp(ui, server)

标签: rshiny

解决方案


server零件改成这个怎么样

server <- function(input, output) {
  output$factors_weight_one_two <- renderUI({
    fluidRow(
      column(6, numericInput(
        "factors_weight_one",
        "Factor 1", 20,
        min = 1, max = 100,
        width = "90%")),
      column(6, numericInput(
        "factors_weight_two",
        "Factor 2", 20,
        min = 1, max = 100,
        width = "90%"))
    )
  })
  output$weight_message <- renderText({

      req(input$factors_weight_one, input$factors_weight_two)

      if (input$factors_weight_one + input$factors_weight_two  != 40) {
        sprintf('<font color="%s">%s</font>', 'red', "Your weights don't sum to 40")
      }  else {
        sprintf('<font color="%s">%s</font>', 'red', "")
      }

  })

}

我用来检查andreq的“真实性” 。顺便说一句,你不应该需要返回输入,因为它已经是.input$factors_weight_oneinput$factors_weight_twoas.numericnumericInputnumeric


推荐阅读