I'm trying to create a column in a data frame which accepts user input and automatically updates reactive values. I'm able to create the column and the values automatically update but my issue is that I also need to allow users to delete rows from the data frame. When I delete rows from the data frame it breaks. My reproducible example is below.
#Simple example
library(shiny)
library(data.table)
library(DT)
library(shinyjs)
library(shinythemes)
library(lpSolve)
server <- function(input, output,session) {
shinyInput <- function(FUN, len, id, ...) {
inputs <- character(len)
for (i in seq_len(len)) {
inputs[i] <- as.character(FUN(paste0(id, i), ...))
}
inputs
}
shinyInput2 = function(FUN, len, id, val, ...) {
inputs = character(len)
for (i in seq_len(len)) {
inputs[i] = as.character(FUN(paste0(id, i), label = NULL,value=round(as.numeric(val[i]),1), ...))
}
inputs
}
# obtain the values of inputs
shinyValue = function(id, len) {
unlist(lapply(seq_len(len), function(i) {
value = input[[paste0(id, i)]]
if (is.null(value)) NA else value
}))
}
Data<-data.frame(Proj=1:10)
Data$Exclude<-shinyInput(actionLink, nrow(Data), '', label = p(tags$b("X"),align="center",style="color:red; font-size:100%; text-align:center;")
, onclick = 'Shiny.onInputChange(\"deleteRows\",
this.id)' )
Data$Proj<-shinyInput2(numericInput, nrow(Data), 'Proj_', Data$Proj,width='40px')
values <- reactiveValues(dfWorking = Data)
hid<-reactive({
shinyValue('Proj_',nrow(values$dfWorking))
})
output$table <- renderDataTable({
datatable(values$dfWorking,escape = FALSE,selection='single',rownames=FALSE
,options = list(pageLength=nrow(values$dfWorking)
,autoWidth = TRUE
,preDrawCallback = JS('function() {
Shiny.unbindAll(this.api().table().node()); }')
,drawCallback = JS('function() {
Shiny.bindAll(this.api().table().node()); } ')
#aoColumnDefs = list(list(sWidth="300px", aTargets=c(list(0),list(1)))) # custom column size
)
)
}
,server=FALSE
)
observeEvent(input$deleteRows, {
values$dfWorking <- values$dfWorking[-as.numeric(input$table_cell_clicked$row),]
})
output$text<-renderPrint({hid()})
}
ui <- fluidPage(dataTableOutput("table"),verbatimTextOutput("text"))
shinyApp(ui = ui, server = server)
(I can provide more detail on what I've tried to solve my problem but I thought it may be a simple problem and so I've kept the example as simple as possible for clarity.)