这是基于您引用的 Shiny 示例的完整示例。这使用来自ggplot2 的mpg 数据。
首先,您可以创建一个reactive 表达式来确定哪些行应该被过滤并显示在表格中。每当您的inputs 之一发生变化时,就会重新评估reactive 表达式。要访问过滤后的数据,您可以引用 filtered_rows()(注意括号)。
要获取选定的行,您可以使用input$table_rows_selected,因为您的dataTableOutput 被称为table(只需附加“_rows_selected”)。这可以是一行或多行,并返回行号(例如,上面示例中的 8)。然后,要提取您的数据,您可以使用filtered_rows()[input$table_rows_selected, c("model", "trans")],其中将包含过滤行的model 和trans 列数据。
verbatimTextOutput 和toString 仅显示验证和演示的结果。您也可以在其他上下文中使用结果。
library(shiny)
library(DT)
library(ggplot2)
ui <- fluidPage(
titlePanel("Basic DataTable"),
# Create a new Row in the UI for selectInputs
fluidRow(
column(4,
selectInput("man",
"Manufacturer:",
c("All",
unique(as.character(mpg$manufacturer))))
),
column(4,
selectInput("trans",
"Transmission:",
c("All",
unique(as.character(mpg$trans))))
),
column(4,
selectInput("cyl",
"Cylinders:",
c("All",
unique(as.character(mpg$cyl))))
)
),
# Create a new row for the table.
DT::dataTableOutput("table"),
verbatimTextOutput("text")
)
server <- function(input, output) {
# Filter data based on selections
filtered_rows <- reactive({
data <- mpg
if (input$man != "All") {
data <- data[data$manufacturer == input$man,]
}
if (input$cyl != "All") {
data <- data[data$cyl == input$cyl,]
}
if (input$trans != "All") {
data <- data[data$trans == input$trans,]
}
data
})
# Show filtered data in the datatable
output$table <- DT::renderDataTable(DT::datatable({ filtered_rows() }))
# Show selected text
output$text <- renderText({ toString(filtered_rows()[input$table_rows_selected, c("model", "trans")]) })
}
shinyApp(ui, server)