r-是否有类似于Shiny fileInput的函数来保存输出



Shiny有一个很好的fileInput()功能,允许用户浏览目录并选择要上传到应用程序的文件。摘自https://shiny.rstudio.com/reference/shiny/1.7.0/fileInput.html,这是MWE:

ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose CSV file to upload", accept = ".csv"),
checkboxInput("header", "Header", TRUE)
),
mainPanel(
tableOutput("contents")
)
)
)

server <- function(input, output) {
output$contents <- renderTable({
file <- input$file1
ext <- tools::file_ext(file$datapath)

req(file)
validate(need(ext == "csv", "Please upload a csv file"))

read.csv(file$datapath, header = input$header)
})
}

shinyApp(ui, server)

我在我的应用程序中使用它来检索数据,我真的很喜欢它。然而,我正在寻找一个类似的功能,用户可以通过浏览目录选择保存文件的位置并选择文件名,以类似的方式保存运行应用程序产生的数据帧。关键是能够浏览本地目录。有什么想法可以做到这一点吗?优选地以与CCD_ 2一样简单的方式。

文件将是.csv,不过我也在考虑.xls。

您可以在ui中使用downloadButton,在server中使用downloadHandler,如下所示:

library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose CSV file to upload", accept = ".csv"),
checkboxInput("header", "Header", TRUE),
downloadButton("download")
),
mainPanel(
tableOutput("contents"),
)
)
)
server <- function(input, output) {
output$contents <- renderTable({
file <- input$file1
ext <- tools::file_ext(file$datapath)

req(file)
validate(need(ext == "csv", "Please upload a csv file"))

read.csv(file$datapath, header = input$header)
})

output$download <- downloadHandler(
filename = function() {
paste0(input$file1, ".csv")
},
content = function(file) {
write.csv(contents(), file)
}
)
}
shinyApp(ui, server)

这里有一个非常基本的示例,当您单击操作按钮时,它会调用file.choose

library(shiny)
shinyApp(
ui = 
fluidPage(
textInput(inputId = "txt_to_save", 
label = "Enter text to save to a file"),
actionButton(inputId = "btn_save_txt", 
label = "Save Text to File")
),

server = 
shinyServer(function(input, output, session){

observeEvent(
input$btn_save_txt, 
{
dest_file <- file.choose()
write(input$txt_to_save, 
dest_file)
}
)

})
)

在实践中,如果您希望文件名由应用程序创建,但目录由用户选择,那么您也可以使用choose.dir()

最新更新