下载反应式数据框/数据表问题

时间:2019-07-10 17:57:43

标签: r shiny download handler reactive

我是R的新手,但我的任务是创建一个工作下载按钮,该按钮将查询表中的数据下载到.csv文件中。当前,我在理解应该传递给write.csv()函数的内容时遇到了麻烦。我知道我必须使查询表具有反应性,但我也不确定如何做到这一点。我在当前代码中遇到的错误是“ 无法将类“ c(“ datatables”,“ htmlwidget”)”强制转换为data.frame”

我尝试将df()函数作为参数传递,但它不起作用。

#ui
column(3, 
                         conditionalPanel("input.table.period != '1980'", 
                                          # only prompt for rcp if a future period (not historical)
                                          # input: select rcp
                                          selectInput("table.rcp", "Emissions Scenario:", 
                                                      c("Medium" = "45",
                                                        "High" = "85")),
                                          downloadButton('downloadData', 'Download')
                                          )


#server  
server <- function(input, output) {
currentdf <- reactive({


# build query based on user-selections
if (input$table.stype == "ann") {
  col.name <- columns.annual[grep(input$table.var, columns.annual)]
  if (input$table.period == "1980") {
    query <- paste0("SELECT ", col.name, ", subbasin, gcm_id FROM hydro_ann WHERE (period = ", input$table.period,
                    ")")
  } else {
    query <- paste0("SELECT ", col.name, ", subbasin, gcm_id FROM hydro_ann WHERE (period = ", input$table.period,
                    ") AND (rcp = ", input$table.rcp, ")")
  }
} else {
  col.name <- columns.month[grep(input$table.var, columns.month)]
  if (input$table.period == "1980") {
    query <- paste0("SELECT ", col.name, ", subbasin, gcm_id, calendar_month FROM hydro_month WHERE (period = ", input$table.period,
                    ")")
  } else {
    query <- paste0("SELECT ", col.name, ", subbasin, gcm_id, calendar_month FROM hydro_month WHERE (period = ", input$table.period,
                    ") AND (rcp = ", input$table.rcp, ")")
  }
}


df <- dbGetQuery(db, query)

DT::df


  })
  output$querytable <- renderTable({ DT::datatable(currentdf()) })
  output$downloadData <- downloadHandler(
filename = function() {
  paste("QueriedData", "csv", sep = ".")
},
content = function(file) {
  write.csv(as.data.frame(currentdf()),file)
}

1 个答案:

答案 0 :(得分:0)

我尝试了解决方案宽度虹膜数据集,该数据集可以让您选择要保存的数据类型,然后再根据选择的选项下载数据...

library(shiny)
library(shinydashboard)
library(DT)
library(datasets)
library(xlsx)

ui <- dashboardPage(
  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(),
  dashboardBody(
    # Boxes need to be put in a row (or column)
    fluidRow(
      box(
        DTOutput("dtable")
          )
    )
  )
)

server <- function(input, output) {
  myModal <- function() {
    div(id = "Download_DATA",
        modalDialog(downloadButton("download1","Download iris as CSV"),
                    br(),
                    br(),
                    downloadButton("download2","Download iris as XLSX"),
                    easyClose = TRUE, title = "Download Table")
    )
  }

  output$dtable <- renderDT(
    datatable(iris,
              extensions = 'Buttons',
              options = list(
                dom = 'Bfrtip',
                buttons = list(
                  list(
                    extend = "collection",
                    text = 'Download',
                    action = DT::JS("function ( e, dt, node, config ) {
                                    Shiny.setInputValue('Download_DATA', true, {priority: 'event'});
}")
                  )
                    )
                  )
                )
              )

  observeEvent(input$Download_DATA, {
    showModal(myModal())
  })


  output$download1 <- downloadHandler(
    filename = function() {
      paste("data-", Sys.Date(), ".csv", sep="")
    },
    content = function(file) {
      write.csv(iris, file)
    }
  )

  output$download2 <- downloadHandler(
    filename = function() {
      paste("data-", Sys.Date(), ".xlsx", sep="")
    },
    content = function(file) {
      write.xlsx(iris, file)
    }
  )

}

shinyApp(ui, server)

请让我知道......