繁体   English   中英

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

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

初学者到R,在这里闪亮! 试图做一个最小的工作示例......我想检查一个无功输入值的条件。 我究竟做错了什么?

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)

错误消息:

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

你只需要对你的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)

John Paul的上述答案当然是可以接受的,但我认为你可能希望看到另一种方式作为你学习过程的一部分。 我会让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)

这是我的尝试。 1)如上所述,您不需要在反应上下文中包含输入$ a并另存为x。 只需使用输入$ a 2)在这个简单的例子中你不需要reactiveValues。 只需将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