josh453
josh453

Reputation: 318

Shiny Data table display all data using filter

I can create a data table in shiny that shows data for any individual buffalo but I can't figure out how to display all buffalo data at the same time. Any help is appreciated.

Sample Data:

cleanbuffalo <- data.frame(name = c("queen","toni","pepper"), longitude = c(31.8,32,33), latitude = c(-24,-25,-26))

Shiny UI:

shinyUI(navbarPage("Buffalo Migration", id ="nav",
  tabPanel("Data",
    fluidRow(
      column(3,
        selectInput("allnamesbuffalo", "Buffalo", c("All Buffalo" = "all buffalo", vars))
        )
      ),
      hr(),
      DT::dataTableOutput("buffalotable")
    )
  )
)

Shiny Server:

shinyServer(function(input, output, session) {
    observe({
    allnamesbuffalo <- if (is.null(input$allnamesbuffalo)) character(0) else       {
          filter(cleanbuffalo, name %in% input$allnamesbuffalo) %>%
         `$`('name') %>%
         unique() %>%
         sort()
      }
    })

  output$buffalotable <- DT::renderDataTable({
    df <- cleanbuffalo %>%
      filter(
        cleanbuffalo$name == input$allnamesbuffalo,
        is.null(input$allnamesbuffalo) | name %in% cleanbuffalo$name
      )
      action <- DT::dataTableAjax(session,df)

      DT::datatable(df, options = list(ajax = list(url = action)),
                    escape = FALSE)
  })
})

Upvotes: 0

Views: 1704

Answers (1)

Xiongbing Jin
Xiongbing Jin

Reputation: 12097

Here is a working example. Note that I added stringsAsFactors=F in your data frame, otherwise you need to use levels(cleanbuffalo$name) to get the names.

library(shiny)
library(dplyr)

cleanbuffalo <- data.frame(name = c("queen","toni","pepper"), 
                           longitude = c(31.8,32,33), 
                           latitude = c(-24,-25,-26), stringsAsFactors = F)

ui <- shinyUI(fluidPage(

  titlePanel("Example"),

  sidebarLayout(
    sidebarPanel(
      selectInput("allnamesbuffalo", "Buffalo", c("all", cleanbuffalo$name))
    ),

    mainPanel(
      dataTableOutput("buffalotable")
    )
  )
))

server <- shinyServer(function(input, output, session) {

  output$buffalotable <- renderDataTable({
    names <- NULL
    if (input$allnamesbuffalo == "all") {
      names <- cleanbuffalo$name
    } else {
      names <- input$allnamesbuffalo
    }
    filter(cleanbuffalo, name %in% names)
  })

})

shinyApp(ui = ui, server = server)

Upvotes: 1

Related Questions