首页 > 解决方案 > R Shiny:从选定行获取数据

问题描述

我想从表中提取数据以用于计算。

我的出发点是 https://shiny.rstudio.com/gallery/basic-datatable.html

本质上,我希望能够选择一行(比如第 8 行)并从中获取模型 =“a4 quattro”和 trans =“manual(m5)”。

我已经寻找示例,但看不到如何应用它。(在我看来)应该简单的东西似乎非常复杂。

这是我第一次使用 R-shiny 应用程序的第一天,我肯定迷路了。

有人可以帮忙吗?

标签: rshinyreactive

解决方案


这是基于您引用的 Shiny 示例的完整示例。这使用mpg来自 的数据ggplot2

首先,您可以创建一个reactive表达式来确定哪些行应该被过滤并显示在表中。每当您input的其中一个发生变化时,reactive就会重新评估表达式。要访问过滤后的数据,您可以引用 as filtered_rows()(注意括号)。

要获取选定的行,您可以使用input$table_rows_selecteddataTableOutput调用table(只需附加“_rows_selected”)。这可以是一行或多行,并返回行号(例如,上面示例中的 8)。然后,要提取数据,您可以使用filtered_rows()[input$table_rows_selected, c("model", "trans")]which 将包含modeltrans列数据用于过滤的行。

verbatimTextOutputtoString简单地显示验证和演示的结果。您也可以在其他上下文中使用结果。

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)

推荐阅读