Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Shiny conditionalPanel displays when condition is not met

Tags:

r

shiny

This is essentially a follow-up with detailed example of this question (no answer came through): conditionalPanel in shiny (doesn't seem to work)

Example app: Displays panels ("list1", "list2", etc.) based on user-selection. "list3" was not selected and should not display.

ui.R

displayList <- c("list1", "list2", "list3")

shinyUI(pageWithSidebar(
  headerPanel("Shiny Display List"),

  sidebarPanel(
    checkboxGroupInput('dlist', 'Display List:', displayList, selected = displayList[1:2])
  ),

  mainPanel(
    h4("Display List"),

    conditionalPanel(condition = "length(intersect(input.dlist, displayList[1])) > 0",
      p("Some List 1 entries")
    ),

    conditionalPanel(condition = "length(intersect(input.dlist, displayList[2])) > 0",
      p("Some List 2 entries")
    ),

    conditionalPanel(condition = "length(intersect(input.dlist, displayList[3])) > 0",
      p("Some List 3 entries") #WASN'T SELECTED, SHOULD NOT DISPLAY INITIALLY
    )
  )
))

server.R

shinyServer(function(input, output) {
  observe({cat(input$dlist, "\n")})
  observe({cat(length(intersect(input$dlist, "list3")))})
})

To test if the condition was met, I ran observe in server.R and the output shows that indeed the condition was not met for panel 3 ("0" below).

list1 list2 
0

But, the app still displays "list3"

enter image description here

Any idea why? I did try different forms of the condition (instead of using intersect etc.) but with no success.

EDIT WITH ANSWER

As @nstjhp & @Julien Navarre point out, the conditionalPanel "condition" needs to be in Javascript. For the example above it works as follows:

conditionalPanel(condition = "input.dlist.indexOf('list1') > -1",
      p("Some List 1 entries")
    )
like image 649
harkmug Avatar asked Mar 10 '14 16:03

harkmug


1 Answers

As @nstjhp said the condition has to be in Javascript into a conditional panel, you can't insert R logic here.

If you want to control the inputs with a R syntax you can use renderUI :

For example :

output$panel = renderUI({
    if(input$dlist[1] == TRUE) {
        display something 
    } else if 
.....

Though the condition isn't very different in javascript in your case. It's juste something like : condition = "input.dlist[0]". Note that in javascript indexes start from 0 and not from 1 like in R.

Your main panel :

mainPanel(
  h4("Display List"),

  conditionalPanel(condition = "input.dlist[0]",
                   p("Some List 1 entries")
  ),

  conditionalPanel(condition = "input.dlist[1]",
                   p("Some List 2 entries")
  ),

  conditionalPanel(condition = "input.dlist[2]",
                   p("Some List 3 entries")
  )
)
like image 162
Julien Navarre Avatar answered Nov 04 '22 21:11

Julien Navarre