The below R Shiny code uses the rhandsontable
package for a user input table. I have set minRows=1
so there is always at least one row present in the table. However, if there is one remaining row and the user tries deleting that remaining row, as the code currently works the row is not deleted but the values in that row are erased. How do I modify the code so that in the scenario where there is only 1 remaining row containing values and the user attempts to delete that last remaining row, the values in that row are preserved?
library(shiny)
library(rhandsontable)
ui <- fluidPage(rHandsontableOutput("myTable"))
server <- function(input, output) {
initial_data <- data.frame(
Column1 = c(1, 2, 3),
Column2 = c("A", "B", "C")
)
output$myTable <- renderRHandsontable({
rhandsontable(initial_data, contextMenu = TRUE, minRows = 1)
})
}
shinyApp(ui, server)
The addition of an observer around the myTable
object and some conditionals take care of this issue where the table should never be blank after deleting rows down to the minimum of one row:
library(shiny)
library(rhandsontable)
ui <- fluidPage(rHandsontableOutput("myTable"))
server <- function(input, output, session) {
initial_data <- data.frame(
Column1 = c(1, 2, 3),
Column2 = c("A", "B", "C")
)
last_good_first_row <- reactiveVal(initial_data[1, , drop = FALSE]) # store initial 1st row
output$myTable <- renderRHandsontable({
rhandsontable(initial_data, contextMenu = TRUE, minRows = 1)
})
observeEvent(input$myTable, {
latest_data <- hot_to_r(input$myTable)
# Check if the first row contains NA or NULL values
if (any(is.na(latest_data[1, ]))) {
latest_data[1, ] <- last_good_first_row() # replace with last known good 1st row
rhandsontable(latest_data, contextMenu = TRUE, minRows = 1)
} else {
last_good_first_row(latest_data[1, , drop = FALSE])
}
output$myTable <- renderRHandsontable({
rhandsontable(latest_data, contextMenu = TRUE, minRows = 1)
})
})
}
shinyApp(ui, server)