r语言 - Shiny,如何从datatable调用过滤器功能?



假设我有下面的代码,我想让radioButtons筛选一个数据。表上的'vs'列= 0或1,这是可能的吗?

我希望过滤renderDataTable(不是mtcars),以便您可以继续使用'_rows_selected'功能等。

library(DT)
ui <- basicPage(
h2("The mtcars data"),
radioButtons("vs_radio", label="filter on vs",
c("0" = "0",
"1" = "1"), inline = TRUE),
DT::dataTableOutput("mytable")
)
server <- function(input, output) {
output$mytable = DT::renderDataTable({
mtcars
})
}
shinyApp(ui, server)

假设您对获取mtcars数据集的原始行索引感兴趣,您可以使用行索引向mtcars添加一个额外的列。稍后,您可以使用响应式表达式中的单选按钮过滤新数据集。您可以在renderDataTable上使用options来隐藏额外的列。最后,您可以使用_rows_selected通过读取响应数据集的附加列(row)来检索原始行索引。也许有更好的解决方案,但下面的代码可能有用。

library(shiny)
library(DT)
ui <- basicPage(
h2("The mtcars data"),
radioButtons("vs_radio", label="filter on vs",
c("0" = "0",
"1" = "1"), inline = TRUE),
DT::dataTableOutput("mytable"),
h4("Selected rows:"),
verbatimTextOutput("selectedRows")

)
server <- function(input, output) {
# add an additional column with the row index of the original dataset
dat <- mtcars
dat$row <- 1:nrow(dat)
# react to the radio button to filter dataset
filteredDat <- reactive({
vs <- as.numeric(input$vs_radio)
dat[dat$vs == vs, ]
})
output$mytable = DT::renderDataTable({
filteredDat()},
options = list(
# hide column "row"
columnDefs = list(list(targets = 12, visible = FALSE))
)
)

output$selectedRows <- renderPrint({ 
idx <- input$mytable_rows_selected
filteredDat()[idx, "row"]
})
}
shinyApp(ui, server)

最新更新