R - 下载过滤的数据表

时间:2017-01-11 17:27:02

标签: r shiny dt

我希望能够在使用内置搜索过滤数据表之后下载数据表。要么是能够使用数据表中使用的相同类型的搜索过滤数据帧,要么访问数据表上的搜索。

2 个答案:

答案 0 :(得分:4)

如果使用客户端处理,则可以使用输入对象input[["tablename_rows_all"]]完成此操作。 (将_rows_all附加到数据表输出槽的名称)

_rows_all对象将返回数据框的行索引。您可以在downloadHandler内使用它来在启动下载时对数据框进行子集化。

library(shiny)
library(DT)

shinyApp(
  ui = 
    shinyUI(
      fluidPage(
        DT::dataTableOutput("dt"),

        p("Notice that the 'rows_all' attribute grabs the row indices of the data."),
        verbatimTextOutput("filtered_row"),


        downloadButton(outputId = "download_filtered",
                       label = "Download Filtered Data")
      )
    ),

  server = 
    shinyServer(function(input, output, session){
      output$dt <- 
        DT::renderDataTable(
          datatable(mtcars,
                    filter = "top"),
          server = FALSE
        )

      output$filtered_row <- 
        renderPrint({
          input[["dt_rows_all"]]
        })


      output$download_filtered <- 
        downloadHandler(
          filename = "Filtered Data.csv",
          content = function(file){
            write.csv(mtcars[input[["dt_rows_all"]], ],
                      file)
          }
        )
    })
)

答案 1 :(得分:0)

跟随this link

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()[input[["ex1_rows_all"]], ],file)
    }
  )
}

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