conditionalPanel in R/shiny

Quick question on conditionalPanel for shiny/R.

Using a slightly modified code example from RStudio, consider the following simple shiny app:

n <- 200


# Define the UI
ui <- bootstrapPage(
   numericInput('n', 'Number of obs', n),
   conditionalPanel(condition = "input.n > 20",
     plotOutput('plot') ),
   HTML("Bottom")
)

# Define the server code
server <- function(input, output) {
   output$plot <- renderPlot({
      if (input$n > 50) hist(runif(input$n)) else return(NULL)
   })
}

# Return a Shiny app object
shinyApp(ui = ui, server = server)

My objective is to hide the graph and move up the HTML text to avoid a gap. Now, you can see that if the entered value is below 20, the graph is hidden and the text "Bottom" is moved up accordingly. However, if the entered value is larger than 20, but smaller than 50, the chart function returns NULL, and while no chart is shown, the text "Bottom" is not moving up.

Question is: is there a way I can set a conditionalPanel such that it appears/is hidden based on whether or not a plot function returns NULL? The reason I'm asking is because the trigger a bit complex (among other things it depends on the selection of input files, and thus needs to change if a different file is loaded), and I'd like to avoid having to code it on the ui.R file.

Any suggestions welcome,

Philipp


Hi you can create a condition for conditionalPanel in the server like this :

n <- 200
library("shiny")

# Define the UI
ui <- bootstrapPage(
  numericInput('n', 'Number of obs', n),
  conditionalPanel(condition = "output.cond == true", # here use the condition defined in the server
                   plotOutput('plot') ),
  HTML("Bottom")
)

# Define the server code
server <- function(input, output, session) {
  output$plot <- renderPlot({
    if (input$n > 50) hist(runif(input$n)) else return(NULL)
  })
  # create a condition you use in the ui
  output$cond <- reactive({
    input$n > 50
  })
  outputOptions(output, "cond", suspendWhenHidden = FALSE)
}

# Return a Shiny app object
shinyApp(ui = ui, server = server)

Don't forget to add the session in your server function and the outputOptions call somewhere in that function.

链接地址: http://www.djcxy.com/p/89140.html

上一篇: R闪亮的动作按钮来影响无功控制

下一篇: R / shiny中的条件面板