R блестящий - возникли проблемы с загрузкой файлов - PullRequest
0 голосов
/ 28 января 2019

Итак, я хочу иметь блестящую страницу, которая: A) позволяет пользователю загружать файл .xls;B) предлагает этот файл обратно пользователю для загрузки в виде файла .csv;C) Печатает заголовок файла в приложении Shiny, чтобы убедиться, что он правильно прочитан.

Вот код, который я использую:

# Want to read xls files with readxl package
library(readxl)
library(shiny)

## Only run examples in interactive R sessions
if (interactive()) {

  ui <- fluidPage(
    fileInput("file1", "Choose File", accept = ".xls"),
    tags$hr(),
    uiOutput("downloader"),
    htmlOutput("confirmText", container = tags$h3),
    tableOutput("listContents")
    )

  server <- function(input, output) {

    theOutput <- reactiveValues(temp = NULL, df = NULL, msg = NULL, fn = NULL)

    observeEvent(input$file1, {
      theOutput$fn <- paste('data-', Sys.Date(), '.csv', sep='')
      theOutput$temp <- read_xls(input$file1$datapath)
      theOutput$msg <- paste("File Contents:")
      theOutput$df <- write.csv(theOutput$temp, 
                                file = theOutput$fn, 
                                row.names = FALSE)
    })

    output$confirmText <- renderText({
      theOutput$msg
    })

    output$listContents <- renderTable({
      head(theOutput$temp)
    })

    output$downloader <- renderUI({
      if(!is.null(input$file1)) {
        downloadButton("theDownload", label = "Download")
        }
      })

    output$theDownload <- downloadHandler(
      filename = theOutput$fn,
      content = theOutput$df
      )
  }

  shinyApp(ui, server)
}

Страница Shiny отображается правильно, онабез проблем принимает загрузку, без проблем распечатывает заголовок .csv и создает правильно отформатированный файл «data- {сегодняшняя дата} .csv» в том же каталоге, что и файл app.R.

Проблема в том, что когда я нажимаю кнопку загрузки, я получаю сообщение об ошибке:

Warning: Error in download$func: attempt to apply non-function                                                    
  [No stack trace available]

Может кто-нибудь сказать мне, что я делаю неправильно?

1 Ответ

0 голосов
/ 28 января 2019

Благодаря комментариям выше, это решение, которое я нашел (с добавлением моих комментариев, чтобы показать, где изменился код):

library(readxl) 
library(shiny) 
if (interactive()) {
    ui <- fluidPage(
    fileInput("file1", "Choose File", accept = ".xls"),
    tags$hr(),
    uiOutput("downloader"),
    htmlOutput("confirmText", container = tags$h3),
    tableOutput("listContents")
    )
     server <- function(input, output) {

    theOutput <- reactiveValues(temp = NULL, msg = NULL)

    observeEvent(input$file1, {
      # Do not try to automate filename and the write.csv output here!
      theOutput$temp <- read_xls(input$file1$datapath)
      theOutput$msg <- paste("File Contents:")
    })

    output$confirmText <- renderText({
      theOutput$msg
    })

    output$listContents <- renderTable({
      head(theOutput$temp)
    })

    output$downloader <- renderUI({
      if(!is.null(input$file1)) {
        downloadButton("theDownload", label = "Download")
        }
      })

    output$theDownload <- downloadHandler(
      # Filename and content need to be defined as functions 
      # (even if, as with filename here, there are no inputs to those functions)
      filename = function() {paste('data-', Sys.Date(), '.csv', sep='')},
      content = function(theFile) {write.csv(theOutput$temp, theFile, row.names = FALSE)}
      )   }
     shinyApp(ui, server) }

Тот факт, что контент принимает аргумент (названный здесь "theFile"), который больше нигде не называется, это то, что сбило меня с толку.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...