1

当在数据表中选择行并且有人按下“删除行”开关时,我试图从数据框中删除行。input$click_rows_selected 给出所选行的 ID。

我对observeEvent 和observe 的使用似乎有问题,因为代码在我第一次轻弹开关时删除了选定的行。然而,之后,每次我选择一行时,它也会删除该行。关闭开关后如何停止删除行?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")}
 })
4

1 回答 1

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)
于 2017-04-14T17:36:54.013 回答