gpt4 book ai didi

r - Shiny R - 下载表格的结果

转载 作者:行者123 更新时间:2023-12-04 04:58:48 31 4
gpt4 key购买 nike

我是 Shiny 的新手,我创建了一个非常简单的 Shiny 应用程序:

library(shiny)

ui <- fluidPage(
fluidRow(column(7,dataTableOutput('dto')))
)

server <- function(input,output){

output$dto <- renderDataTable({MYTABLE})


}

runApp(list(ui=ui,server=server))

有什么办法可以选择下载表格的结果(不管是 CSV、XLSX...)

干杯

最佳答案

使用 downloadButton() 很容易或 downloadLink()结合 downloadHandler如果你让数据本身成为响应式(Reactive)表达。然后,您可以使用相同的响应式(Reactive)表达式下载发送到输出的任何内容。

一个小例子:

library(shiny)

ui <- fluidPage(
# This one is linked by the id 'download'
downloadButton('download',"Download the data"),
fluidRow(column(7,dataTableOutput('dto')))
)

server <- function(input,output){
# Reactive expression with the data, in this case iris
thedata <- reactive(iris)

output$dto <- renderDataTable({thedata()})
output$download <- downloadHandler(
filename = function(){"thename.csv"},
content = function(fname){
write.csv(thedata(), fname)
}
)

}

runApp(list(ui=ui,server=server))

记住:
  • 参数 contentdownloadHandler必须是一个生成文件的函数!它应该为连接/文件名采用一个参数。在本例中,它是一个 csv 文件,但对于例如图像,您可以使用 png()dev.off() , 对于 ggplots,您可以使用 ggsave() , ...
  • 参数 filename不一定是函数,但我发现它有效
    那样更好。特别是在使用文件名的响应式(Reactive)表达式时。
  • 您链接了 downloadHandlerdownloadButton通过输出列表:downloadButton的id是 downloadHandler 返回的输出元素的名称.

  • 编辑:

    有些人尝试使用 download.file()为此,但这也是错误的。函数 download.file()在用户端使用时工作,而不是服务器端。它允许您将文件从 Internet 下载到调用该函数的计算机。如果你在 Shiny 应用程序中使用它,它会在本地运行时工作。那是因为用户和服务器是同一台机器。但是,在 Shiny 服务器上部署应用程序时, download.file()本质上是将文件下载到服务器,而不是从。

    关于r - Shiny R - 下载表格的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44504759/

    31 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com