问题描述
当试图在数据表中选择行并且有人按下删除行"开关时,我正在尝试从数据框中删除行. input $ click_rows_selected提供所选行的ID.
I am trying to delete the rows from a dataframe when they have been selected in the datatable and someone presses the "Delete Rows" switch. input$click_rows_selected gives the id's of the selected rows.
我对observeEvent和observe的使用似乎有问题,因为代码是在我第一次轻按开关时删除选定的行.但是,此后每次我选择一行时,它也会删除该行.开关关闭后,如何停止删除该行? if和else语句似乎根本没有帮助.
There seems to be something wrong with my use of observeEvent and observe, because the code deletes the selected rows the first time I flick the switch. Afterwards however, every time I select a row it also deletes that row. How do I get to stop deleting the row once the switch has been turned off? The if and else statement don't seem to help at all.
代码的简化版:
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
的做法.
The following code should help you toward a solution.Please note that the practice to have nested observe
should be in general avoided.
我添加了updateCheckboxGroupInput
,因为我认为在示例上下文中这是合理的.
I've added updateCheckboxGroupInput
as I thought it made sense in the context of the example.
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)
这篇关于R闪亮的observeEvent问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!