2017-04-14 124 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)