简体   繁体   English

如何在R(Shiny)中创建具有被动值的IF语句

[英]How to create IF statement with reactive values in R ( Shiny )

Beginner to R and shiny here! 初学者到R,在这里闪亮! Tried to make a minimal working example... I want to check a condition on a reactive input value. 试图做一个最小的工作示例......我想检查一个无功输入值的条件。 What am I doing wrong? 我究竟做错了什么?

library(shiny)

ui<-fluidPage(

  numericInput(inputId="a", label=NULL, value=0),
  textOutput(outputId="out")
)

server <- function(input, output) {
  x <- reactive(input$a)
  if (x() < 4) 
    {y<-1}
  else
  {y<-0}

  output$out <- renderText({y})
}

shinyApp(ui = ui, server = server)

The error message: 错误消息:

Operation not allowed without an active reactive context. 没有活动的反应上下文,不允许操作。 (You tried to do something that can only be done from inside a reactive expression or observer.) (你试图做一些只能在反应式表达式或观察者内部完成的事情。)

You just need to use reactive with your if so that shiny knows that y changes when x does. 你只需要对你的if使用reactive ,以便闪亮知道yx会发生变化。

library(shiny)

ui<-fluidPage(

  numericInput(inputId="a", label=NULL, value=0),
  textOutput(outputId="out")
)

server <- function(input, output) {
  x <- reactive(input$a)
  y <- reactive( if (x()<4) 1 else 0 )

  output$out <- renderText({ y() })
}

shinyApp(ui = ui, server = server)

The answer above from John Paul is certainly acceptable, but I thought you might like to see another way as a part of your learning process. John Paul的上述答案当然是可以接受的,但我认为你可能希望看到另一种方式作为你学习过程的一部分。 I will let StackOverflow sort out which is more advisable. 我会让StackOverflow排除哪个更合适。

library(shiny)

ui<-fluidPage(

  numericInput(inputId="a", label=NULL, value=0),
  textOutput(outputId="out")
)

server <- function(input, output) {
  state <- reactiveValues()

  observe({
    state$x <- input$a
    state$y <- ifelse(state$x < 4, 1, 0)
  })

  output$out <- renderText({ state$y })
}

shinyApp(ui = ui, server = server)

here's my attempt. 这是我的尝试。 1) as stated, you don't need to wrap input$a in reactive context and save as x. 1)如上所述,您不需要在反应上下文中包含输入$ a并另存为x。 just use input$a 2) you don't need reactiveValues in this simple example. 只需使用输入$ a 2)在这个简单的例子中你不需要reactiveValues。 just save y as a reactive variable. 只需将y保存为反应变量。 then, in the renderText, access by calling the function ("y()") 然后,在renderText中,通过调用函数(“y()”)进行访问

library(shiny)

ui<-fluidPage(

  numericInput(inputId="a", label=NULL, value=0),
  textOutput(outputId="out")
)

server <- function(input, output) {

  y <- reactive({
    if (input$a < 4) {
      return(1)
    } else {
      return(0)
    }
  }
  )

  output$out <- renderText({y()})
}

shinyApp(ui = ui, server = server)

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

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