Можно ли очистить отображаемый вывод в ShinyApp с помощью actionButton? - PullRequest
0 голосов
/ 20 января 2019

Я создаю приложение блестящие приложения на данных mtcars .Я получил 2 actionButtons (Go & Clear). Кнопка Go предназначена для отображения выходных данных на главной панели, а кнопка Clear предназначена для очистки этих выходных данных.Кнопка «Очистить» не работает по непредвиденной причине.Может кто-нибудь, пожалуйста, посмотрите на мои коды.Буду очень признателен.

library(shiny)   
library(DT)     
library(dplyr) 
library(shinythemes) 
library(htmlwidgets) 
library(shinyWidgets) 
library(shinydashboard)

data_table<-mtcars

#ui
ui = fluidPage( 
  sidebarLayout(
    sidebarPanel (

      uiOutput("cyl_selector"),
      uiOutput("disp_selector"),

      actionButton(inputId = "go", label = "Go"),
      actionButton(inputId = "reset", label = "Clear")),


    mainPanel(
           DT::dataTableOutput('mytable') )))



#server
server = function(input, output, session) {

  output$cyl_selector <- renderUI({

    selectInput(inputId = "cyl",
                label = "cyl:", multiple = TRUE,
                choices = c( unique(as.character(data_table$cyl))),
                selected = c('4')) })


  output$disp_selector <- renderUI({

    available <- data_table[c(data_table$cyl %in% input$cyl ), "disp"]  

    selectInput(
      inputId = "disp", 
      label = "disp:",
      multiple = TRUE,
      choices = c('All',as.character(unique(available))),
      selected = 'All') })


  thedata <- eventReactive(input$go,{

    data_table<-data_table[data_table$cyl %in% input$cyl,]


    if(input$disp != 'All'){
      data_table<-data_table[data_table$disp %in% input$disp,]
    }

    data_table
 })


 # thedata <- eventReactive(input$reset,{
 #   data_table<-NULL
 # })


  output$mytable = DT::renderDataTable({

    DT::datatable( filter = "top",  rownames = FALSE, escape = FALSE,
                   options = list(pageLength = 50, autowidth=FALSE,
                                  dom = 'Brtip'  ),
                   {     
                     thedata()   # Call reactive thedata()
                   })
 })}  
shinyApp(ui = ui, server = server)

Ответы [ 2 ]

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

Почему бы не добавить какой-нибудь JavaScript? Таким образом, ваш код практически не меняется.

Создайте файл js в вашей блестящей папке со следующим кодом (rmDt.js в этом примере):

$("#reset").click(function() {
  $(".display.dataTable.no-footer").DataTable().destroy();
  $(".display.dataTable.no-footer").DataTable().clear().draw();    
  $(".display.no-footer").DataTable().destroy();
  $(".display.no-footer").DataTable().clear().draw();    
});

Сохраните этот файл, а затем вставьте его в свой блестящий скрипт R:

library(shiny)   
library(DT)     
library(dplyr) 
library(htmlwidgets) 
library(shinyWidgets) 
library(shinydashboard)

data_table<-mtcars

#ui
ui = fluidPage(
  sidebarLayout(
    sidebarPanel (
      uiOutput("cyl_selector"),
      uiOutput("disp_selector"),

      actionButton(inputId = "go", label = "Go"),
      actionButton(inputId = "reset", label = "Clear"),
      includeScript(path ="rmDt.js") # inject javascript
      ),

    mainPanel(
      DT::dataTableOutput('mytable') ))
  )



#server
server = function(input, output, session) {

  output$cyl_selector <- renderUI({

    selectInput(inputId = "cyl",
                label = "cyl:", multiple = TRUE,
                choices = c( unique(as.character(data_table$cyl))),
                selected = c('4')) })


  output$disp_selector <- renderUI({

    available <- data_table[c(data_table$cyl %in% input$cyl ), "disp"]  

    selectInput(
      inputId = "disp", 
      label = "disp:",
      multiple = TRUE,
      choices = c('All',as.character(unique(available))),
      selected = 'All') })


  thedata <- eventReactive(input$go,{

    data_table<-data_table[data_table$cyl %in% input$cyl,]


    if(input$disp != 'All'){
      data_table<-data_table[data_table$disp %in% input$disp,]
    }

    data_table
  })

  output$mytable = DT::renderDataTable({

    DT::datatable( filter = "top",  rownames = FALSE, escape = FALSE,
                   options = list(pageLength = 50, autowidth=FALSE,
                                  dom = 'Brtip'  ),
                   {     
                     thedata()   # Call reactive thedata()
                   })
  })}  
shinyApp(ui = ui, server = server, options = list(launch.browser = T))
0 голосов
/ 20 января 2019

insertUI() и removeUI() - это то, что вы можете искать.

Удаление элемента проще с removeUI():

  observeEvent(input$reset, {
    removeUI("#mytable")
  })

Чтобы избежать его удалениянавсегда вы можете использовать insertUI():

  observeEvent(input$go, {
    insertUI("#placeholder", "afterEnd", ui = DT::dataTableOutput('mytable'))
  })

Чтобы правильно разместить элемент, вы можете использовать заполнитель в mainPanel():

mainPanel(
  tags$div(id = "placeholder")
)

Затем вы можете удалить зависимостьthedata() от кнопки ввода, так как вы используете insertUI() сейчас.(Вам следует перейти к insertUI(), потому что в противном случае вы не сможете повторно вставить таблицу, как только она будет удалена без нее, ...)

  thedata <- reactive({
     ...
  })

Полный пример будет выглядеть так:

library(shiny)   
library(DT)     
library(dplyr) 
library(shinythemes) 
library(htmlwidgets) 
library(shinyWidgets) 
library(shinydashboard)

data_table<-mtcars

#ui
ui = fluidPage( 
  sidebarLayout(
    sidebarPanel (

      uiOutput("cyl_selector"),
      uiOutput("disp_selector"),

      actionButton(inputId = "go", label = "Go"),
      actionButton(inputId = "reset", label = "Clear")),


    mainPanel(
      tags$div(id = "placeholder")
    )
  )
)



#server
server = function(input, output, session) {

  output$cyl_selector <- renderUI({

    selectInput(inputId = "cyl",
                label = "cyl:", multiple = TRUE,
                choices = c( unique(as.character(data_table$cyl))),
                selected = c('4')) })


  output$disp_selector <- renderUI({

    available <- data_table[c(data_table$cyl %in% input$cyl ), "disp"]  

    selectInput(
      inputId = "disp", 
      label = "disp:",
      multiple = TRUE,
      choices = c('All',as.character(unique(available))),
      selected = 'All') })


  thedata <- reactive({
    input$go
    isolate({

      data_table<-data_table[data_table$cyl %in% input$cyl,]


      if(input$disp != 'All'){
        data_table<-data_table[data_table$disp %in% input$disp,]
      }

      return(data_table)
    })
  })

  observeEvent(input$reset, {
    removeUI("#mytable")
  })

  observeEvent(input$go, {
    insertUI("#placeholder", "afterEnd", ui = DT::dataTableOutput('mytable'))
  })


  output$mytable = DT::renderDataTable({

    DT::datatable( filter = "top",  rownames = FALSE, escape = FALSE,
                   options = list(pageLength = 50, autowidth=FALSE,
                                  dom = 'Brtip'  ),
                   {     
                     thedata()   # Call reactive thedata()
                   })
  })}  
shinyApp(ui = ui, server = server)
)
...