2
votes

I want to use an if condition in a shiny DT::renderDataTable, but it does not work properly. Here is a minimal example:

library(DT)
library(shiny)

ui <- shinyUI(fluidPage(
  titlePanel(""),

  sidebarLayout(
    sidebarPanel(radioButtons("button", "", choices=c("a", "b"))),
      mainPanel(DT::dataTableOutput("table1")) 
  )
))

server <- function(input, output){
 x <- data.frame(col1 = 1:2, col2 = 3:4, col3 =5:6)
 y <- data.frame(col1 = 10:11, col2 = 20:21)

 output$table1 <- DT::renderDataTable({
   if(input$button == "a"){
     datatable(x)
   }
   if(input$button == "b"){
     datatable(y)
   }
   })
}

shinyApp(ui, server)

The app does not show any output, if "a" is chosen but works perfectly if "b" is chosen. Does anyone have an idea? Thanks.

1

1 Answers

2
votes

If you change your if structure to an else if it will work.

server <- function(input, output){   
    x <- data.frame(col1 = 1:2, col2 = 3:4, col3 =5:6)   
    y <- data.frame(col1 = 10:11, col2 = 20:21)
    output$table1 <- DT::renderDataTable({
        if(input$button == "a"){
          datatable(x)
        }
        else if(input$button == "b"){
          datatable(y)
        }   
    }) 
}

The reactive element takes the last thing from inside the {}. I guess your second if returns NULL when a is selected.