R Shiny: Update datatable with checkbox

时间:2019-01-09 21:40:46

标签: r shiny datatables dt

I want to dynamically populate a table and update a list of items selected using the checkbox.

Here is my attempt. I report some random data points into a table and uncheck some of them expecting the list at the bottom of the plot to change.

The list is correctly updated only when unchecking the last item but not the others.

Any suggestions?

enter image description here enter image description here

library(shiny)
library(DT)

ui <- fluidPage(
    fluidRow(
    column(4,
        plotOutput("plot1", click = "plot_click"),
        textInput("collection_txt",label="Foo")),
    column(4,
    DT::dataTableOutput("table"))
    )
)


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

    # collect data points

    x <- reactiveValues(selected = '')
    y <- reactiveValues(selected = '')
    observeEvent(input$plot_click, {
        x$x <- c(x$x,input$plot_click$x)
        y$y <- c(y$y,input$plot_click$y)
    })

    output$plot1 <- renderPlot({
        plot(1,1, type='n')
        points(x$x,y$y)
    })

    # populate the table

    shinyInput <- function(FUN,id,num,...) {
        inputs <- character(num)
        for (i in seq_len(num)) {
            inputs[i] <- as.character(FUN(paste0(id,i),label=NULL,...))
        }
        inputs
    }

    output$table = DT::renderDataTable({
        tab <- data.frame('x'=x$x ,'y'=y$y)
        DT::datatable(cbind(tab, Selected=shinyInput(checkboxInput,"srows_",nrow(tab),value=TRUE,width=1)),
                                options = list(orderClasses = TRUE,
                                   drawCallback= JS(
                                     'function(settings) {
                                     Shiny.bindAll(this.api().table().node());}'),
                                   dom = 't', searching=FALSE),
                                selection='none',escape=F)
    })

    # show the list of selected items

    rowSelect <- reactive({
      rows=names(input)[grepl(pattern = "srows_",names(input))]
      paste(unlist(lapply(rows,function(i){
        if(input[[i]]==T){
          return(substr(i,gregexpr(pattern = "_",i)[[1]]+1,nchar(i)))
        }
      })))
    })

    observe({
      updateTextInput(session, "collection_txt", value = rowSelect() ,label = "Selected:" )
    })

}


shinyApp(ui, server)

1 个答案:

答案 0 :(得分:0)

单击一个点时,必须在创建新表之前取消先前创建的Shiny对象的绑定。例如使用shinyjs

library(shinyjs)
ui <- fluidPage(
  useShinyjs(),
  fluidRow(
    ......


  observeEvent(input$plot_click, {
    runjs("Shiny.unbindAll($('#table').find('table').DataTable().table().node());")
    x$x <- c(x$x,input$plot_click$x)
    y$y <- c(y$y,input$plot_click$y)
  })

enter image description here