简体   繁体   English

R Shiny:根据观察事件中的反应表达式检查条件

[英]R Shiny: Check condition based on reactive expressions in observeEvent

I would like to build a Shiny App with two tabs:我想构建一个带有两个选项卡的 Shiny 应用程序:

In one tab, some values are entered as input.在一个选项卡中,输入一些值作为输入。 In the next tab, the user can find an output that is based on the values entered in the first tab.在下一个选项卡中,用户可以找到基于在第一个选项卡中输入的值的 output。

However, before proceeding to the output I want to check if summing up three entries will give the fourth entry.但是,在继续 output 之前,我想检查三个条目的总和是否会给出第四个条目。 To do so, I want to use reactive expressions that contain the values of the different entries.为此,我想使用包含不同条目值的反应式表达式。

Here is an example of what I would like to do:这是我想做的一个例子:

# clean environment
rm(list = ls(all = TRUE))

library(shiny)

# Create user interface (UI)
u <- tagList(
  navbarPage(
    # UI for input
    title = "",
    id = "Example_App",
    tabPanel("Model input",
             fluidRow(
               column(11, offset = 0,  
                      br(), 
                      h4("Model input"),
                      br(), 
                      sidebarPanel(
                        div(textInput('str_Input1', 'Input 1\n', "",
                                     placeholder = "5.6, 6.7, 4.1"), class = "subheading"),
                        div(textInput('str_Input2', 'Input 2\n', "",
                                      placeholder = "5.6, 6.7, 4.1"), class = "subheading"),
                        div(textInput('str_Input3', 'Input 3\n', "",
                                      placeholder = "5.6, 6.7, 4.1"), class = "subheading"),
                        div(textInput('str_Input4', 'Input 4\n', "",
                                      placeholder = "5.6, 6.7, 4.1"), class = "subheading"),
                        actionButton('jumpToModelOutput', 'Run')),
                      mainPanel(
                        h4('You entered'),
                        verbatimTextOutput("oid_Input1"),
                        verbatimTextOutput("oid_Input2"),
                        verbatimTextOutput("oid_Input3"),
                        verbatimTextOutput("oid_Input4"))))),
    # UI for output
    tabPanel("Model output",
             fluidRow(
               column(11, offset = 0,
                      br(),
                      h4('Your output will be here.'))
                      ))))

# Define server output
s <- shinyServer(function(input, output, session) {

  # Define reactive expressions
  num_Input1 <- reactive(as.numeric(unlist(strsplit(input$str_Input1,","))))
  num_Input2 <- reactive(as.numeric(unlist(strsplit(input$str_Input2,","))))
  num_Input3 <- reactive(as.numeric(unlist(strsplit(input$str_Input3,","))))
  num_Input4 <- reactive(as.numeric(unlist(strsplit(input$str_Input4,","))))
  
  # Define server output for input check
  output$oid_Input1 <- renderPrint({
    cat("Input 1:\n")
    print(num_Input1())
    })
  output$oid_Input2 <- renderPrint({
    cat("Input 2:\n")
    print(num_Input2())
  })
  output$oid_Input3 <- renderPrint({
    cat("Input 3:\n")
    print(num_Input3())
  })
  output$oid_Input4 <- renderPrint({
    cat("Input 4:\n")
    print(num_Input4())
  })
  
  
  # Check if conditions are fulfilled before switching to Model output
  observeEvent(input$jumpToModelOutput, {
     if(!all.equal((num_Input1() + num_Input2() + num_Input3()),num_Input4())){
       showNotification("Error.", type = "error")
     }else{
          updateTabsetPanel(session, "Example_App",
                            selected = "Model output")
        }})

})

# Create the Shiny app 
shinyApp(u, s)

When I enter "1,2,3" into all tabs and press the button, the App stops and I get the following message: "Listening on http://127.0.0.1:3925 Warning: Error in: invalid argument type"当我在所有选项卡中输入“1,2,3”并按下按钮时,应用程序停止并收到以下消息:“Listening on http://127.0.0.1:3925警告:错误:无效参数类型”

Removing the: gives the following message: Warning: Error in if argument is not interpretable as logical删除:给出以下消息:警告:如果参数不可解释为逻辑错误

As far as I get the messages, the reactive expressions are not interpreted as numeric (?) but summing them up and printing them gives correct results.就我收到的消息而言,反应式表达式不会被解释为数字(?),但将它们相加并打印会给出正确的结果。

Could anyone please help me finding the problem?谁能帮我找到问题?

The issue is that all.equal returns a string containing a report of the difference in the passed values.问题是all.equal返回一个字符串,其中包含传递值差异的报告。 That's why the docs (see ?all.equal ) state:这就是文档(参见?all.equal )state 的原因:

Do not use all.equal directly in if expressions—either use isTRUE(all.equal(....)) or identical if appropriate.不要在 if 表达式中直接使用 all.equal——如果合适,可以使用 isTRUE(all.equal(....)) 或相同。

Hence, to fix your issue wrap inside isTRUE :因此,要解决您的问题,请将其包含在isTRUE

observeEvent(input$jumpToModelOutput, {
    if (!isTRUE(all.equal(num_Input1() + num_Input2() + num_Input3(), num_Input4()))) {
      showNotification("Error.", type = "error")
    } else {
      updateTabsetPanel(session, "Example_App",
        selected = "Model output"
      )
    }
  })

在此处输入图像描述

all.equal returns a string if the elements are not equal, and you can't use a !如果元素不相等, all.equal返回一个字符串,并且不能使用! on a string.在一个字符串上。 You can first check with isTRUE if it's TRUE or not and then negate it (note: you can't use isFALSE because in case it's not TRUE , all.equal returns a string).您可以先用isTRUE检查它是否为TRUE ,然后将其取反(注意:您不能使用isFALSE因为如果它不是TRUEall.equal返回一个字符串)。 If you expect the elements to be exactly equal, you could use identical to make things easier.如果您希望元素完全相等,则可以使用identical的方法使事情变得更容易。

I've also summed up all element in each input before adding them, is this what you wanted to do?在添加它们之前,我还总结了每个输入中的所有元素,这是你想要做的吗?

# Check if conditions are fulfilled before switching to Model output
  observeEvent(input$jumpToModelOutput, {
    if(!isTRUE(all.equal((sum(num_Input1()) + sum(num_Input2()) + sum(num_Input3())),sum(num_Input4())))){
      showNotification("Error.", type = "error")
    }else{
      updateTabsetPanel(session, "Example_App",
                        selected = "Model output")
    }})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM