【问题标题】:R Shiny observeEvent issuesR闪亮的observeEvent问题
【发布时间】:2017-04-14 15:49:54
【问题描述】:

当在数据表中选择行并且有人按下“删除行”开关时,我正在尝试从数据框中删除行。 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")}
 })

【问题讨论】:

  • input$deleterows是什么类型的控件?
  • 这是一个复选框输入
  • 你能把它改成actionButton还是需要一个复选框?
  • 我将其更改为复选框,因为操作按钮存在完全相同的问题。一旦你按下它,它就会永远保持它的状态。我认为该复选框可能会解决我的问题,因为我可以在其中放置一个 if 和 else 语句。它也失败了。
  • 由于问题不在于复选框或按钮,您仍应使用按钮,除非您希望行为有所不同:即选中复选框后,每次单击都会立即删除行。使用按钮时,预期行为应该是单击时删除选定的行。

标签: r datatable shiny rstudio shinybs


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    • 2018-07-30
    • 2018-05-02
    • 2018-05-08
    • 1970-01-01
    • 2020-05-24
    相关资源
    最近更新 更多