R Shiny observeEvent issues

拈花ヽ惹草 提交于 2019-12-02 08:09:09

问题


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")}
 })

回答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)


来源:https://stackoverflow.com/questions/43414932/r-shiny-observeevent-issues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!