首页 > 解决方案 > 根据用户对 radioButtons() 的选择,使用 downloadHandler() 动态下载闪亮的文件

问题描述

我有一个闪亮的应用程序,它根据用户输入创建一个数据框。我想制作一个动态下载按钮,该按钮需要用户选择(radioButton)来下载动态制作的数据框。数据帧作为列表从函数返回

当我为两个不同的下载按钮创建功能时,下载工作正常

library(shiny)
library(DT)

temp_func <- function(){
  x <- mtcars
  y = x[,1]
  return(list(complete_df = as.data.frame(x), column1 = as.data.frame(y)))
}

# UI
ui <- shinyUI({
  fluidPage(
    actionButton("fetch", label = "Fetch data first"),
    
    mainPanel(DT::dataTableOutput("table")),
    
    downloadButton("down_all", "Download all"),
    downloadButton("down_c1", "Download c1")
    
)})

# Server
server <- Main_Server <- function(input,output,session){
  
  # Reactive Values
  values <- reactiveValues(table = NULL)
  
  # fetchEvent (Consider temp_func() is fetching data from website)
  observeEvent(input$fetch, {values$table <- temp_func()})
  
  # Rendering table for display
  output$table <- renderDT({datatable(values$table$complete_df)})
  
  # Download 1
  output$down_all <- downloadHandler(
    filename = function() { paste("All columns","csv", sep=".")},
    content = function(file) {write.csv(values$table$complete_df, file)})
  
  # Download 2
  output$down_c1 <- downloadHandler(
    filename = function() { paste("Columns1","csv", sep=".")},
    content = function(file) {write.csv(values$table$column1, file)})
}

# Run-app
shinyApp(ui, server)

一旦我合并这两个函数并input$choice从单选按钮传递,我会得到一个空文件

library(shiny)
library(DT)

temp_func <- function(){
  x <- mtcars
  y = x[,1]
  return(list(complete_df = as.data.frame(x), column1 = as.data.frame(y)))
}

# UI
ui <- shinyUI({
  fluidPage(
    actionButton("fetch", label = "Fetch data first"),
    
    mainPanel(DT::dataTableOutput("table")),
    
    radioButtons("rd", c("Select"), choices = c("All Columns" = "complete_df","Column 1" = "column1"),
                 selected = "complete_df"),
    downloadButton("down", "Download")
    
  )})

# Server
server <- Main_Server <- function(input,output,session){
  
  # Reactive Values
  values <- reactiveValues(table = NULL)
  
  # fetchEvent (Consider temp_func() is fetching data from website)
  observeEvent(input$fetch, {values$table <- temp_func()})
  
  # Rendering table for display
  output$table <- renderDT({datatable(values$table$complete_df)})
  
  # Combined Download
  output$down <- downloadHandler(
    filename = function() { paste("File","csv", sep=".")},
    content = function(file) {write.csv(values$table$input$rd, file)})
  
}

# Run-app
shinyApp(ui, server)

考虑 temp_func() 正在从其他网站获取数据

标签: rshiny

解决方案


尝试使用:

 # Combined Download
  output$down <- downloadHandler(
    filename = function() { paste("File","csv", sep=".")},
    content = function(file) {write.csv(values$table[[input$rd]], file)})

您使用的语法返回NULL,因为values$table没有input字段。
使用更新的语法,下载的文件不再是空的。


推荐阅读