R Shiny observeEvent 问题

R Shiny observeEvent issues

我试图在数据表中 selected 并且有人按下 "Delete Rows" 开关时从数据框中删除行。 input$click_rows_selected 给出 selected 行的 id。

我对 observeEvent 和 observe 的使用似乎有问题,因为代码在我第一次轻按开关时删除了 selected 行。但是之后,每次我 select 一行时,它也会删除该行。开关关闭后如何停止删除行? if 和 else 语句似乎根本没有帮助。

代码的简化版本:

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

以下代码应该可以帮助您找到解决方案。 请注意,通常应避免嵌套 observe 的做法。

我添加了 updateCheckboxGroupInput,因为我认为它在示例的上下文中有意义。

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)