Shiny中DataTable排序后行ID选择异常问题求助
问题描述
我开发了一个Shiny应用,使用nc数据集渲染名为table的DataTable,需求是点击actionButton()时选中ID为2的行。初始代码如下:
dataTableProxy("table") %>% # 取消之前选中的行 selectRows(NULL) %>% # 选中ID为2的行 selectRows(which(input$table_rows_all == 2))
未排序时代码正常工作,但对表格排序后行为异常:比如按PERIMETER列排序后,点击按钮会选中ID为15的行(排序后第5行),而非预期的ID为2的Alleghany县行。其他列排序时也存在同样问题。
最小可复现代码:
# Load packages ---- library(shiny) library(sf) # User interface ---- ui <- fluidPage( sidebarLayout( sidebarPanel(width=4, style = "height: 90vh; overflow-y: auto; margin: 0px;", actionButton("select", label="Select row with id = 2") ), mainPanel(width=8, style = "margin: 0px;", "Table", tags$style('#table :is(th, td) {padding: 4px;}'), div(dataTableOutput(outputId = "table"), style = "height: calc(47vh); font-size: 75%; width: 100%;"), br(), br(), verbatimTextOutput('printfield') ) ) ) # Server logic ---- server <- function(input, output) { nc <- st_read(system.file("shape/nc.shp", package="sf")) %>% st_transform(crs=4326) output$table <- DT::renderDataTable({DT::datatable(st_drop_geometry(nc), selection= "single", options = list(scrollX = TRUE, scrollY = "47vh", dom = 't', paging = FALSE))}) observeEvent(input$table_rows_selected, { output$printfield <- renderPrint({input$table_rows_selected}) }) observeEvent(input$select, { if (input$select%%2==1) { dataTableProxy("table") %>% selectRows(NULL) %>% selectRows(which(input$table_rows_all == 2)) }else{ dataTableProxy("table") %>% selectRows(NULL) } }) } # Run the app shinyApp(ui, server)
解决方案
将selectRows(which(input$table_rows_all == 2))替换为selectRows(2)即可:
dataTableProxy("table") %>% selectRows(NULL) %>% selectRows(2)
原因解释
input$table_rows_all返回的是当前表格排序/过滤后的行索引,当表格排序后,这个索引会发生变化,导致which(input$table_rows_all == 2)指向的不再是原始数据中ID为2的行。而直接传入2给selectRows(),会直接定位到原始数据中第2行(对应ID为2的记录),不受排序操作影响。
内容的提问来源于stack exchange,提问作者Wander Demuynck
相关产品推荐
相关产品推荐

