我想從表中提取資料以用于計算。
我的起點是 https://shiny.rstudio.com/gallery/basic-datatable.html
本質上,我希望能夠選擇一行(比如第 8 行),然后從中獲取模型 = "a4 quattro" 和 trans = "manual(m5)"。
我已經尋找了例子,但看不到如何應用它。對于(在我看來)應該很簡單的事情來說,這似乎非常復雜。
這是我第一個 R-shiny 應用程式的第一天,我肯定迷路了。
有人可以幫忙嗎?
uj5u.com熱心網友回復:
這是一個基于您參考的 Shiny 示例的完整示例。這使用mpg來自ggplot2.
首先,您可以創建一個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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/352301.html
