Как показать все данные до применения фильтров в приборной панели R Shiny - PullRequest
0 голосов
/ 12 января 2019

Я хочу показать полные данные до того, как будет выбран какой-либо фильтр, а затем установить подмножество данных в соответствии с выбором фильтра.

Например: - Если ничего не выбрано, то должны отображаться все записи - Если выбран только континент, а фильтры страны и штата не выбраны, то на нем должны отображаться все записи этого конкретного континента. - Если выбраны Континент и Страна, то должны отображаться все записи выбранного континента и выбранной страны. - Если выбраны фильтры континента, страны и штата, то должны отображаться только записи этих параметров выбранных фильтров

Вот мой код и ссылка на набор данных https://www.dropbox.com/s/5ii7fkt4anedjpb/R%20Codes.zip?dl=0

library(shinyjs)
library(stats)
library(shinydashboard)
library(sqldf)
library(shiny)
library(ggplot2)
library(stats)
library(lubridate)
library(DT)
library(sqldf)


setwd('C:\\Users\\folder')

header <- dashboardHeader(
  title = "Shiny Dashboard")
sidebar <- dashboardSidebar(
  sidebarMenu(
    menuItem("Data", tabName = "ShowData", icon = icon("dashboard")),
    menuItem("Summary", tabName = "ShowSummary", icon = icon("bar-chart-o"))
  )
)

body <- dashboardBody(
  useShinyjs(),
  tabItems(
    tabItem(tabName = "ShowData",
            DT::dataTableOutput("table")
    ),
    tabItem(tabName = "ShowSummary",
            box(width =3,
                h3("Tutorial by TopBullets.com"),
                helpText("Please Continent, Country and State Combition"),
                uiOutput("continent"),
                uiOutput("country"),
                uiOutput("state")
            ),

            box(width =9,
                DT::dataTableOutput("table_subset")
            ))  ))

# Put them together into a dashboardPage
ui <- dashboardPage(header,sidebar,body)

options(shiny.maxRequestSize = 15*1024^2)
server <- function(input,output){

  # Importing data and save it temporary in data variable
  data <- reactive({
    read.table(file = "C:\\Users\\folder\\Countries-Continents-csv.csv",
               sep = ",", header = T,
               stringsAsFactors = F)
  })

  # Showing the original data
  output$table <- DT::renderDataTable({
    if(is.null(data())){return()}
    DT::datatable(data(), options = list(scrollX = T))
  })

  # Creating filters
  output$continent <- renderUI({
    selectInput(inputId = "Continent", "Select Continent",choices = var_continent(), selected = "Asia")
  })
  output$country <- renderUI({
    selectInput(inputId = "Country", "Select Country",choices = var_country(), selected = "India")
  })
  output$state <- renderUI({
    selectInput(inputId = "State", "Select State",choices = var_state(),selected = "Goa")
  })

  # Cascasing filter for state

  var_continent <- reactive({
    file1 <- data()
    if(is.null(data())){return()}
    as.list(unique(file1$Continent))
  })

  # Creating reactive function to subset data
  continent_function <- reactive({
    file1 <- data()
    continent <- input$Continent
    file2 <- sqldf(sprintf("select * from file1 where Continent = '%s' ", continent))
    return (file2)

  })

  var_country <- reactive({
    file1 <- continent_function()
    if(is.null(file1)){return()}
    as.list(unique(file1$Country))

  })


  state_function <- reactive({
    file1 <- continent_function()
    country <- input$Country
    file2 <- sqldf(sprintf("select * from file1 where Country = '%s' ", country))
    return (file2)

  })

  var_state <- reactive({
    file1 <- state_function()
    as.list(unique(file1$State))
  })

  output$table_subset <- DT::renderDataTable({
    file1 <- state_function()
    state <- input$State
    file2 <- sqldf(sprintf("select * from file1 where State = '%s' ", state))
    DT::datatable(file2, options = list(scrollX = T))

  })

}
shinyApp(ui,server)

1 Ответ

0 голосов
/ 13 января 2019

На вкладке сводки вы можете добавить запись «Все» в верхнюю часть каждого selectInput и выполнять фильтрацию только в том случае, если выбранный континент / страна / штат не «Все». Чтобы сделать это для ввода континента, вы должны иметь:

as.list(c("All", unique(file1$Continent)))

Тогда реактивная функция для получения данных о континенте будет выглядеть так:

continent_function <- reactive({
  file1 <- data()
  continent <- input$Continent
  sql = "select * from file1"
  if(continent != "All") {
    sql = paste(sql, sprintf("where Continent = '%s' ", continent))
  }
  file2 <- sqldf(sql)
  return (file2)
})

(и аналогично для страны и штата.)

...