【发布时间】:2019-01-28 19:16:05
【问题描述】:
所以我想要一个闪亮的页面: 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 的头部,并在同一文件中创建一个格式正确的“数据-{今天的日期}.csv”文件目录作为 app.R 文件。
问题是,当我点击下载按钮时,我收到错误消息:
Warning: Error in download$func: attempt to apply non-function
[No stack trace available]
谁能告诉我我做错了什么?
【问题讨论】:
-
我猜是因为您将包含
write.csv的变量传递给downloadHandler 的内容函数。保存write.csv参数不是常见的做法,虽然我看到你想要做什么,但我不知道这是否可能。也许使用content=write.csv(theOutput$temp, file = theOutput$fn, row.names = FALSE)虽然我从不使用 reactiveValues 所以我不确定下载处理程序是否能很好地接受这些。 -
content参数期望接收将创建文件的函数。当您输入:theOutput$df <- write.csv(...时,您没有存储带有指定参数的函数,而是保存了write.csv返回的值,因此会出现错误。您应该将write.csv移动到您的downloadHandler函数中 -
你们俩都是对的——但同样的事情也必须为
filename做。我将发布我的解决方案作为答案。