r - Using a reactive expression in an if statement in shiny -


i writing shiny app output should depend on value of variable calculated in reactive expression in shiny. instead of reproducing actual app believe have recreated problem following simple app:

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 number greater 10"})      else output$oid2<-renderprint({"you entered number less or equal  10"})    } ) 

if run error: error in .getreactiveenvironment()$currentcontext() :`

operation not allowed without active reactive context. (you tried can done inside reactive expression or observer.)

if change if statement to: if (x>50) ... error:

error in x > 50 : comparison (6) possible atomic , list types

when change if statement to: if (reactive({(x>50)})) ... error message:

error in if (reactive({ : argument not interpretable logical

i'd appreciate help

a couple problems. first , biggest problem don't seem understand how reactivity works. error says "operation not allowed without active reactive context" , that's problem - you're accessing x() inside server function's main body not within reactive context. render* function reactive context example. solve simple have move if statement inside renderprint.

the other small problem output ids don't match (verbatimtextoutput("odic") vs output$oid2).

if don't understand reactivity, highly suggest take half hour understand better. this tutorial has section on reactivity can helpful, or can re-read official shiny tutorial rstudio.

here's code fixed app (i removed bunch of useless ui elements)

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 number greater 10"     } else {       "you entered number less or equal 10"     }   }) } shinyapp(ui = ui, server = server) 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -