【问题标题】:Download filtered data from renderDataTable() in Shiny从 Shiny 中的 renderDataTable() 下载过滤后的数据
【发布时间】:2018-01-29 03:08:40
【问题描述】:

我正在尝试允许用户从 Shiny 中的 renderDataTable() 下载过滤后的数据。例如,在下面的 MWE 中,用户应该能够转到“查看整个数据表”选项卡,例如,只为变量 2 选择“蓝色”值。然后,他们应该能够单击“下载过滤后的数据”按钮并查看过滤后的数据。

但是,如下面的代码所示,当用户单击“下载过滤后的数据”按钮时,他们会下载整个(未过滤的)数据。我看过其他示例(例如R - Download Filtered Datatable)并尝试将它们合并到我的代码中,但仍然卡住了。任何建议都会很有帮助。谢谢。

# Load packages
library(shiny)
library(tidyr)
library(dplyr)

# Load data
data_table <- data.frame(Variable1 = sample(LETTERS, 1000, replace=TRUE), Variable2 = sample(c("Orange","Green","Blue","Pink"), 1000, replace=TRUE), Variable3 = sample(c("Square","Triangle","Circle"), 10000, replace=TRUE))

# Define UI
ui <- fluidPage(
  tabsetPanel(type = "tabs", id="tabs",
    tabPanel("Column Summary", value=2,
       sidebarPanel(uiOutput("sidebar_summary")),
       verbatimTextOutput("summary")),
    tabPanel("See Whole Data Table", value=5,
       downloadButton('downLoadFilter',"Download the filtered data"),
       verbatimTextOutput("Raw"),
       DT::dataTableOutput('ex1'))
  )
)

# Define server logic
server <- function(input, output) {

  output$sidebar_summary <- renderUI({
    if (input$tabs == 2){
    print("This is a tab with information.")
    }
  })

  thedata <- reactive(data_table)

  output$Raw <- renderPrint({
    if(input$tabs == 5){
      output$ex1 <- DT::renderDataTable(DT::datatable(thedata(), filter = 'top',escape = FALSE, options = list(pageLength = 10, scrollX='500px',autoWidth = TRUE)))
    }
  })

  output$downLoadFilter <- downloadHandler(
    filename = function() {
      paste('Filtered data-', Sys.Date(), '.csv', sep = '')
    },
    content = function(file){
      write.csv(thedata(),file)
    }
  )
}

# Create Shiny object
shinyApp(ui = ui, server = server)

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    从您提供的link 复制示例似乎可行。

    你只需要替换

    output$downLoadFilter <- downloadHandler(
        filename = function() {
          paste('Filtered data-', Sys.Date(), '.csv', sep = '')
        },
        content = function(file){
          write.csv(thedata(),file)
        }
      )
    

    在你的服务器中使用

     output$downLoadFilter <- downloadHandler(
        filename = function() {
          paste('Filtered data-', Sys.Date(), '.csv', sep = '')
        },
        content = function(file){
          write.csv(thedata()[input[["ex1_rows_all"]], ],file)
        }
      )
    

    这就是诀窍。希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 2021-11-20
      • 2018-10-08
      • 1970-01-01
      • 2019-12-21
      • 2019-04-29
      • 2017-05-26
      • 2019-11-01
      • 1970-01-01
      • 2021-12-13
      相关资源
      最近更新 更多