Lee88
Lee88

Reputation: 1295

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

Beginner to R and shiny here! 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.)

Upvotes: 14

Views: 22409

Answers (3)

travismark
travismark

Reputation: 51

here's my attempt. 1) as stated, you don't need to wrap input$a in reactive context and save as x. just use input$a 2) you don't need reactiveValues in this simple example. just save y as a reactive variable. then, in the renderText, access by calling the function ("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)

Upvotes: 4

timelyportfolio
timelyportfolio

Reputation: 6579

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. I will let StackOverflow sort out which is more advisable.

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)

Upvotes: 8

John Paul
John Paul

Reputation: 12654

You just need to use reactive with your if so that shiny knows that y changes when x does.

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)

Upvotes: 12

Related Questions