Hi all,
I searched the web for while but could not solve this problem with shiny and DT: The aim is to update the value of cell in a datable when the user clicks on the corresponding cell. I observe() the "cells_selected" input of the table and call the corresponding function to update the value. The problem is that the function gets called in a infinite loop. Somehow, resetting the cell selection to NULL does not seem to work. See below for a minimal working example. Any hint is welcome!
library(shiny)
library(DT)
ui <- fluidPage(
#A minimal GUI
mainPanel(
DT::dataTableOutput("DemoTable")
)
)
server <- function(input, output) {
#A reactive data frame with some initialization
DemoTable <- data.frame(
value1 = runif(0,1,n=4),
value2 = runif(0,1,n=4)
)
makeReactiveBinding("DemoTable")
#Link the demo table reactive to the output datatable
output$DemoTable = DT::renderDataTable({
MyDT <- datatable(data=DemoTable,selection=list(mode="single",target="cell"))
return(MyDT)
})
#A function to change the value in the selected cell
UpdateValue <- function(row,col) {
tmp <- DemoTable
tmp[row,col] <- runif(0,1,n=1)
DemoTable <<- tmp
}
#Observe cell select event of table
AnyCellSelected <- reactive({!is.null(input$DemoTable_cells_selected)})
observe({
#Catch some irrelavant conditions
if ( !AnyCellSelected() ) return()
DemoTableSelectedCell <- input$DemoTable_cells_selected
if ( nrow(DemoTableSelectedCell) == 0 ) return()
#Extract selected cell indices
RowSelected <- DemoTableSelectedCell[1,1]
ColSelected <- DemoTableSelectedCell[1,2]
#Unselect the selected cell to avoid repeated call of this
#observe() function - does not work
DTproxy <- DT::dataTableProxy(outputId="DemoTable")
DT::selectCells(DTproxy, NULL)
#Report to console whether this function is called for
#debugging purpose - gets called over and over again.
print("called")
#Change the value in the selected cell on selection
UpdateValue(row=RowSelected,col=ColSelected)
})
}
# Run the application
shinyApp(ui = ui, server = server)