2017-04-14 69 views
1

我试图删除数据表中的行,当他们在数据表中被选中,并且某人按下“删除行”开关。输入$ click_rows_selected给出所选行的ID。R Shiny observeEvent问题

我使用observeEvent似乎有什么问题,并观察,因为代码在第一次轻弹开关时删除选定的行。不过,每次我选择一行时,它也会删除该行。一旦开关关闭,我该如何停止删除行? 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")} 
}) 
+0

输入$ deleterows'是什么类型的控件? –

+0

这是一个复选框输入 – DS501

+0

您可以将其更改为“actionButton”吗?还是需要成为复选框? –

回答

1

下面的代码应该可以帮助你走向一个解决方案。 请注意,一般应避免嵌套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)