gpt4 book ai didi

r - 如何从筛选数据表 (DT) 的选定行中获取数据?

转载 作者:行者123 更新时间:2023-12-01 17:35:43 27 4
gpt4 key购买 nike

DT 包允许您使用 input$tableID_rows_selected 获取所选行的索引。这对于没有过滤数据的表非常有用。但是,如果我们有一个经过筛选的数据集,则无法使用相同的方法,因为行索引已关闭。

对于过滤后的数据集,我们如何获取数据表中选定行中的数据?

下面,我发布了一个基本的 Shiny 应用程序,其中显示了四个表:第一个是原始 mtcars 数据集,第二个获取第一个中选定的行。第三个和第四个执行相同的操作,但是在“filter”sliderInput 上过滤数据集之后。

library(shiny)
library(DT)
library(dplyr)

ui <- fluidPage(
DT::dataTableOutput("origTable"),
DT::dataTableOutput("origTableSelected"),
sliderInput("filter", label = "Filter by cyl", min = 4, max = 8, step = 2, value = 6),
DT::dataTableOutput("filteredTable"),
DT::dataTableOutput("filteredTableSelected")
)


server <- function(input, output, session) {

output$origTable <- DT::renderDataTable({
datatable(
mtcars,
selection = list(mode = "multiple"),
caption = "Original Data"
)
})

origTable_selected <- reactive({
ids <- input$origTable_rows_selected
mtcars[ids,]
})

output$origTableSelected <- DT::renderDataTable({
datatable(
origTable_selected(),
selection = list(mode = "multiple"),
caption = "Selected Rows from Original Data Table"
)
})

output$filteredTable <- DT::renderDataTable({
datatable(
filter(mtcars, cyl == input$filter),
selection = list(mode = "multiple"),
caption = "Filtered Table (based on cyl)"
)
})

filteredTable_selected <- reactive({
ids <- input$filteredTable_rows_selected
mtcars[ids,]
})

output$filteredTableSelected <- DT::renderDataTable({
datatable(
filteredTable_selected(),
selection = list(mode = "none"),
caption = "Table that gets data from unfiltered original data"
)
})
}

shinyApp(ui = ui, server = server)

最佳答案

一种方法:在filteredTable_selected() 函数中,您要创建要放入第四个DT 中的数据,请像您一样使用filter(mtcars, cyl == input$filter)为您的第三个表而不是 mtcars 执行此操作。这样,行索引就会匹配。

如果您担心较大数据集的性能问题,只需在响应式(Reactive)表达式中过滤数据即可,该表达式会缓存其输出。这样,您就不会过滤超过 input$filter 值更改的内容。

server <- function(input, output, session) {
filteredTable_data <- reactive({
filter(mtcars, cyl == input$filter)
})

output$filteredTable <- DT::renderDataTable({
datatable(
filteredTable_data(),
selection = list(mode = "multiple"),
caption = "Filtered Table (based on cyl)"
)
})

filteredTable_selected <- reactive({
ids <- input$filteredTable_rows_selected
filteredTable_data()[ids,]
})

output$filteredTableSelected <- DT::renderDataTable({
datatable(
filteredTable_selected(),
selection = list(mode = "none"),
caption = "Table that gets data from unfiltered original data"
)
})
}

关于r - 如何从筛选数据表 (DT) 的选定行中获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38511717/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com