r - R Shiny:从选定行获取数据
问题描述
我想从表中提取数据以用于计算。
我的出发点是 https://shiny.rstudio.com/gallery/basic-datatable.html
本质上,我希望能够选择一行(比如第 8 行)并从中获取模型 =“a4 quattro”和 trans =“manual(m5)”。
我已经寻找示例,但看不到如何应用它。(在我看来)应该简单的东西似乎非常复杂。
这是我第一次使用 R-shiny 应用程序的第一天,我肯定迷路了。
有人可以帮忙吗?
解决方案
这是基于您引用的 Shiny 示例的完整示例。这使用mpg
来自 的数据ggplot2
。
首先,您可以创建一个reactive
表达式来确定哪些行应该被过滤并显示在表中。每当您input
的其中一个发生变化时,reactive
就会重新评估表达式。要访问过滤后的数据,您可以引用 as filtered_rows()
(注意括号)。
要获取选定的行,您可以使用input$table_rows_selected
自dataTableOutput
调用table
(只需附加“_rows_selected”)。这可以是一行或多行,并返回行号(例如,上面示例中的 8)。然后,要提取数据,您可以使用filtered_rows()[input$table_rows_selected, c("model", "trans")]
which 将包含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)
推荐阅读
- .net - Yocto Linux 内核:如何将 .NET 核心框架构建到我的 Linux 映像中?
- flutter - 将变量转移到其他类
- java - 是否可以从 dto 和 User 类创建一个 newUser ?
- python - Seaborn 小提琴图与 x 轴标签不对齐
- r - 是否有任何简单/基本的方法可以使用 R 拆分文本转录本?
- html - 如何使用 2 列中的第一项制作响应式网格?
- r - 如何在不构建或安装包的情况下运行 R 包测试?
- flutter - Flutter在滚动时隐藏搜索文本字段
- c - C语言建立指数增长函数X = a(1+b)^t
- javascript - 打字稿使用函数中的第一个参数从接口中查找第二个参数的类型