假设我有一个带有数据表和绘图的 Shiny 应用程序。我希望能够搜索/过滤数据表,并有一个反映结果的图。
我该怎么做呢?这甚至可能吗?有没有办法将过滤后的数据表输出到我可以使用的对象?
这是一个基本的闪亮应用程序,它不起作用。
library(DT)
ui <- basicPage(
h2("The mtcars data"),
DT::dataTableOutput("mytable"),
plotOutput('plot1')
)
server <- function(input, output) {
output$mytable = DT::renderDataTable({
datatable(mtcars,filter = 'top')
})
output$plot1 <- renderPlot({
plot(input$mytable$wt, input$mytable$mpg)
})
}
shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)
正如@r2evans 指出的那样,我对您的代码进行了一些编辑,因为您的方式存在一些错误。
无论如何,您可以使用input$tableId_rows_all. 它给出了所有页面上的行索引(在表被搜索字符串过滤之后)。
在filtered_table()应用所有搜索过滤器后,我的代码为您提供了一个数据框对象。output$test实时显示此表。
library(shiny)
library(DT)
ui <- basicPage(
h2("The mtcars data"),
DT::dataTableOutput("mytable"),
verbatimTextOutput("test"),
plotOutput('plot1')
)
server <- function(input, output) {
mc <- head(mtcars) # could be reactive in real world case
output$mytable = DT::renderDataTable({
datatable(mc, filter = 'top')
})
filtered_table <- reactive({
req(input$mytable_rows_all)
mc[input$mytable_rows_all, ]
})
output$plot1 <- renderPlot({
plot(filtered_table()$wt, filtered_table()$mpg, col = "red", lwd = 10)
})
output$test <- renderPrint({
filtered_table()
})
}
shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)