更改闪亮按钮的标签并计算点击次数

change label of shiny button and counting clicks

我试图切换 show/hide 列按钮的标签,并记录它被点击的次数以改变 [=16= 显示的列数].我做到了,但我无法使用计数器值的直接 even/odd 微分。相反,我不得不使用这个:(vars$counter+1)/2) %% 2 == 0) 来让它工作,因为每次点击都会改变计数器 2 次。我想请求一个更简单的程序,也许有一个 shinyBS 可以吗?

## app.R ##
library(shiny)
library(shinydashboard)
library(DT)

body<-dashboardBody(
  textOutput("count"),
  uiOutput('showallcolumnsbutton'),
  DT::dataTableOutput('table2')
)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  body
)

server <- function(input, output) {
  table<-data.frame(replicate(10,sample(0:1,1000,rep=TRUE)))
  vars<-reactiveValues()
  vars = reactiveValues(counter = 0)
  observe({
    if(!is.null(input$showallcolumns)){
      input$showallcolumns
      isolate({
        vars$counter <- vars$counter + 1
      })
    }
  })
  label <- reactive({
    if(!is.null(input$showallcolumns)){
      if( ( (vars$counter+1)/2) %% 2 == 0) label <- "Hide"
      else label <- "Show"
    }
  })
  output$showallcolumnsbutton <- renderUI({
    actionButton("showallcolumns", label = label(),
                 icon("hand-pointer-o"),
                 style="color: #000; background-color: #0099ff; border-color: #2e6da4" 
    )
  })
  output$count<-renderText({paste("counter value:",vars$counter)})
  columnstoshow = reactive ({
    x=  ((vars$counter+1)/2) # %% 2 == 0)
    if (!is.null (x))
    {
      if (x %% 2 == 0) {
        c=c(1:10)
      }
      else {
        c=c(1:5)
      }
    } #end 1st if
    else {
      c=c(1:10)
    }
  })
  output$table2 = DT::renderDataTable({
    DT::datatable(table[, columnstoshow()])
  })

} # end server

shinyApp(ui, server)

因为我不是100%你想要的,是吗?请注意,我使用了其他库,例如 shinyBS

rm(list = ls())
library(shiny)
library(shinydashboard)
library(DT)
library(shinyBS)

body <- dashboardBody(bsButton("showallcolumns", label = "Hide", block = F, style="danger",icon=icon("hand-pointer-o")),br(),DT::dataTableOutput('table2'))
ui <- dashboardPage(dashboardHeader(),dashboardSidebar(),body)

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

  table <- data.frame(replicate(10,sample(0:1,1000,rep=TRUE)))
  vars <- reactiveValues(counter = 1:10)

  observeEvent(input$showallcolumns,{
    if(input$showallcolumns %% 2){
      updateButton(session, "showallcolumns",label = "Show", block = F, style = "success",icon=icon("hand-pointer-o")) 
      vars$counter <- 1:5
    }
    else{
      updateButton(session, "showallcolumns",label = "Hide", block = F, style = "danger",icon=icon("hand-pointer-o"))    
      vars$counter <- 1:10
    }                                                                                                                        
  })  

  output$table2 = DT::renderDataTable({
    DT::datatable(table[, vars$counter])
  })

} # end server

shinyApp(ui, server)