1

I am trying to delete the rows from a dataframe when they have been selected in the datatable and someone presses the "Delete Rows" switch. input$click_rows_selected gives the id's of the selected rows.

There seems to be something wrong with my use of observeEvent and observe, because the code deletes the selected rows the first time I flick the switch. Afterwards however, every time I select a row it also deletes that row. How do I get to stop deleting the row once the switch has been turned off? The if and else statement don't seem to help at all.

Shortened version of the code:

observeEvent(input$deleterows,{

  if(input$deleterows==TRUE){

  observe({
        if (is.null(input$click_rows_selected))
           return()
        values$df <- values[input$click_rows_selected,]})} else{ 
 print("check")}
 })
DS501
  • 113
  • 1
  • 10
  • What type of control is `input$deleterows`? – John Paul Apr 14 '17 at 16:11
  • It is a checkboxinput – DS501 Apr 14 '17 at 16:17
  • Could you change it to an `actionButton` or does it need to be a check box? – John Paul Apr 14 '17 at 16:20
  • I changed it to a checkbox cause the actionbutton had the exact same problem. Once you push it, it keeps it state forever. I thought the checkbox might solve my issue cause I could put an if and else statement in there. It failed as well. – DS501 Apr 14 '17 at 16:23
  • Since the problem is not with checkbox or button, you should still use button, unless you want the behavior to be different: i.e. with checkbox selected, every click delete rows immediately. With button the expect behavior should be delete selected rows when clicked. – dracodoc Apr 14 '17 at 19:18

1 Answers1

1

The following code should help you toward a solution. Please note that the practice to have nested observe should be in general avoided.

I've added updateCheckboxGroupInput as I thought it made sense in the context of the example.

library(shiny)

values <- reactiveValues(df = iris)

ui <- fluidPage( 

  sidebarLayout(

    sidebarPanel(
      checkboxGroupInput('inputId', label=NULL, choices = colnames(df), selected = NULL,
           inline = FALSE, width = NULL, choiceNames = NULL, choiceValues = NULL),
      actionButton("deleterows", "push to delete") 
    ),

    mainPanel(tableOutput("contents")
    )
  ))

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

  observeEvent(input$deleterows,{
    cols <- setdiff(colnames(values$df), input$inputId)
                    values$df <- values$df[c(cols)]

                    updateCheckboxGroupInput(session, 'inputId', label = NULL, choices = colnames(values$df),
                      selected = NULL, inline = FALSE, choiceNames = NULL,
                      choiceValues = NULL)
 })

output$contents <- renderTable({
        values$df 
  })

}

shinyApp(ui,server)
Enzo
  • 2,543
  • 1
  • 25
  • 38