首页 > 解决方案 > 当数据有效时,R Shiny validate 返回错误

问题描述

我有一个闪亮的应用程序,当没有数据时会产生错误,我正在尝试使用 validate 来产生更好的错误消息。我已经让它适用于没有数据的变量,但是在有数据的地方出现错误,应该出现一个图(或表)。

使用以下代码,我收到以下错误。

else if (input$geo=="Alaska, 2015") {
    data <- switch(
        validate(need(input$var != "Sexual Orientation", "Data Unavailable")),
        input$var, 
        "Housing Status" = hmlweightak,
        "Sex" = sexweightak,
        "Race/Ethnicity" = raceethweightak,
        "Sexual Orientation" = "",
        "Bullied at School in the last 12 Months" = bsweightak,
        "Missed School due to Safety Concerns" = usweightak,
        "Deliberately hurt by an intimate partner" = pvweightak,
        "Forced to Perform Sexual Acts by Intimate Partner in the last 12 Months" = saweightak,
        "Binge Drank in the last 30 days" = bdweightak,
        "First Tried Alcohol by Age 12" = faweightak,
        "First Tried Marijuana by Age 12" = fmweightak,
        "Suffered from Depression in the last 12 Months" = dweightak,
        "Had Suicidal Thoughts in the last 12 Months" = stweightak,
        "Attempted Suicide in the last 12 Months" = asweightak,
        "Required Medical Attention After Suicide Attempt in the last 12 Months" = smweightak,
        "Ever Used Illegal Drugs" = sdweightak,
        "Used Prescription Drugs Without a Prescription" = pdweightak,
        "Sexually Active by Age 13" = fiweightak,
        "Drank or Used Drugs Before Last Sexual Intercourse" = ddliweightak,
        "Breakfast in the Last 7 Days" = "",
        "Average Hours of Sleep per Night" = hsweightak,
        "Used a Condom During Last Sexual Intercourse" = clweightak,
        "Asthma" = aweightak
    )
}

在此处输入图像描述

当我包含get()before时,我也遇到了这个错误input$var,并且在之前的某个时候我遇到了一个不同的错误,它基本上列出了所有变量,但我现在似乎无法重现它。这只是一小部分代码,所以如果更多代码或屏幕截图会有所帮助,请告诉我,但我希望它很简单,因为它似乎只工作了一半。提前致谢!

标签: rvalidationshiny

解决方案


问题在于您的switchandvalidate语句的组合。

假设根据您想要返回一个或另一个数据集的 input$dropDownValue。如果是iris return datasets::iris,您将需要以下语句。

switch(input$dropDownValue,
       iris = datasets::iris,
       cars = datasets::cars)

validate如果第一条语句的计算结果为 ,则停止函数的执行并添加验证消息FALSE

在您的情况下,它应该类似于

validate(need(input$var != "Sexual Orientation", "Data Unavailable"))
data <- switch(input$var, 
               "Housing Status" = hmlweightak,
               "Sex" = sexweightak,
               [...]
               )

validate有关使用and的示例,请参见下面的代码switch

library(shiny)
library(datasets)

ui <- fluidPage(
   selectInput("dropDownValue", "Data", c("no data", "iris", "cars")),
    mainPanel(
      plotOutput("plot")
    )
)

server <- function(input, output) {
  data <- reactive({
    validate(
      need((input$dropDownValue == "iris" || input$dropDownValue == "cars"), "Please select a data set")
    )
    switch(input$dropDownValue,
           iris = datasets::iris,
           cars = datasets::cars)
  })

  output$plot <- renderPlot({
    hist(data()[, 1])
  })
}
shinyApp(ui, server)

推荐阅读