闪亮数据表使用过滤器显示所有数据

时间:2016-08-24 14:56:32

标签: r shiny

我可以创建一个闪亮的数据表,显示任何单个水牛的数据,但我无法弄清楚如何同时显示所有水牛数据。任何帮助表示赞赏。

示例数据:

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

闪亮的用户界面:

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)
  })
})

1 个答案:

答案 0 :(得分:1)

这是一个工作示例。请注意,我在您的数据框中添加了stringsAsFactors=F,否则您需要使用levels(cleanbuffalo$name)来获取名称。

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)