在闪亮的if语句中使用反应式表达式

MSR*_*MSR 8 r shiny

我正在编写一个闪亮的应用程序,其中输出应该取决于变量的值,该变量在闪亮的反应式表达式中计算.而不是复制实际的应用程序,我相信我用以下简单的应用程序重新创建了我的问题:

ui.R file:

   library(shiny)

   shinyUI(pageWithSidebar(

   headerPanel("Illustrating problem"),

   sidebarPanel(

   numericInput('id1', 'Numeric input, labeled id1', 0, min = 0, max = 100, step        =5)

  ),

  mainPanel(

    h4('You entered'),

    verbatimTextOutput("oid1"),

    verbatimTextOutput("odic")

  )
))

server.R file


library(shiny)

shinyServer(

  function(input, output) {

    output$oid1 <- renderPrint({input$id1})

    x<-reactive({5*input$id1})

    if (x()>50) output$oid2<-renderPrint({"You entered a number greater than 10"})

    else output$oid2<-renderPrint({"You entered a number less than or equal to 
10"})

  }
)
Run Code Online (Sandbox Code Playgroud)

如果我像这样运行它然后我得到错误: 错误 .getReactiveEnvironment()$currentContext():`

没有活动的反应上下文,不允许操作.(你试图做一些只能在反应式表达式或观察者内部完成的事情.)

如果我将if语句更改为:if (x>50)...然后我收到错误:

x> 50时出错:比较(6)仅适用于原子和列表类型

当我将if语句更改为:if (reactive({(x>50)}))...然后我收到错误消息:

if(反应({:参数不能解释为逻辑错误)时出错

我非常感谢任何帮助

Dea*_*ali 12

几个问题.第一个也是最大的问题是你似乎并不了解反应性如何起作用.错误显示"没有活动的响应上下文时不允许操作",这就是问题 - 您正在访问x()服务器功能的主体内部,但不是在反应性上下文中.例如,任何render*函数都是反应性上下文.所以要解决这个问题,你必须简单地移动if语句renderPrint.

另一个小问题是你的输出id不匹配(verbatimTextOutput("odic")vs output$oid2).

如果你不了解反应性,我强烈建议你花半个小时来更好地理解它.本教程有一个关于反应性的部分可能会有所帮助,或者您可以重新阅读RStudio的官方闪亮教程.

这是你的固定应用程序的代码(我删除了一堆无用的UI元素)

library(shiny)
ui <- fluidPage(
  numericInput('id1', 'Numeric input, labeled id1', 0, min = 0, max = 100, step=5),
  verbatimTextOutput("oid1"),
  verbatimTextOutput("oid2")

)
server <- function(input, output, session) {
  output$oid1 <- renderPrint({input$id1})

  x<-reactive({5*input$id1})

  output$oid2<-renderPrint({
    if (x()>50) {
      "You entered a number greater than 10"
    } else {
      "You entered a number less than or equal to 10"
    }
  })
}
shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)


Mik*_*ise 5

请注意,Shiny的工作基于事件驱动模型 - 几乎所有以图形为导向的UI(今天绝大多数)都是如此.这不是一个新概念,至少从80年代开始就存在,但它比一个遵循单个流程图的编程更复杂 - 它确实需要一些人习惯.

无论如何,在Shiny中reactive,output并且observe语句必须处于最高级别,我认为没有例外.

你可能想要这样的东西:

library(shiny)

u <- shinyUI(pageWithSidebar(

  headerPanel("Illustrating problem"),

  sidebarPanel(
    numericInput('id1', 'Numeric input, labeled id1', 0, min = 0, max = 100, step =5)
  ),

  mainPanel(

    h4('You entered'),
    verbatimTextOutput("oid1"),
    verbatimTextOutput("oid2")

  )
))

s <- shinyServer(function(input, output) {

    output$oid1 <- renderPrint({input$id1})

    x<-reactive({5*input$id1})

    output$oid2<-renderPrint({
      if (x()>50){
         "You entered a number greater than 10"
      } else {
         "You entered a number less than or equal to 10"
      }
    }
  )
}
)
shinyApp(ui = u, server = s)
Run Code Online (Sandbox Code Playgroud)

产量:

在此输入图像描述