Hello,
I know it has been a while since this was posted, but I was interested in the same functionality. I managed to get it working with the following code. It takes some knowledge of jQuery and Javascript to put it all together.
ui.Rlibrary(shiny)
shinyServer(function(input, output) {
Dataset <- reactive({
df <- mtcars
# If the dataframe used to create the DataTable
# happens to contain NA values, they need to
# be replaced with an empty string. This ensures
# that the array returned from the datatables
# underscore method (i.e. the data contained in
# input$filtered_table) contains an entry in every
# cell. Otherwise the ProcessedFilteredData routine
# will result in corrupted data
df[
is.na(df)] <- ""
return(df)
})
output$data_table <- renderDataTable({
Dataset()
}, options = list(sDom = "ilftpr"))
ProcessedFilteredData <- reactive({
v <- input$filtered_table
# This code assumes that there is an entry for every
# cell in the table (see note above about replacing
# NA values with the empty string).
col_names <- names(Dataset())
n_cols <- length(col_names)
n_row <- length(v)/n_cols
m <- matrix(v, ncol = n_cols, byrow = TRUE)
df <- data.frame(m)
names(df) <- col_names
return(df)
})
output$downloadData <- downloadHandler(
filename = function() { 'filtered_data.csv' }, content = function(file) {
write.csv(ProcessedFilteredData(), file, row.names = FALSE)
}
)
})
server.Rlibrary(shiny)
shinyUI(fluidPage(
tags$head(
tags$style(type="text/css", "tfoot {display: table-header-group}") # Move filters to top of datatable
),
titlePanel("Filtered Data CSV Download"),
sidebarLayout(
sidebarPanel(
HTML('
<script type="text/javascript">
$(document).ready(function() {
$("#downloadData").click(function() {
var filtered_table_data = $("#DataTables_Table_0").dataTable()._("tr", {"filter":"applied"});
Shiny.onInputChange("filtered_table", filtered_table_data);
});
});
</script>
'),
downloadButton('downloadData', 'Download Filtered Data')
),
mainPanel(
dataTableOutput("data_table")
)
)
))
Also, if you have more than one Datatable on your page you may need to change the 0 inside the "#DataTables_Table_0" expression to a different number.
-Kevin