【问题标题】:Download text and generate txt file in Shiny在 Shiny 中下载文本并生成 txt 文件
【发布时间】:2017-12-27 16:22:54
【问题描述】:

我正在寻找一种通过生成 .txt 文件来下载应用程序上显示的文本的方法。这是我的尝试,不幸的是没有成功:

library(shiny)

ui <- fluidPage(

    sidebarPanel(
      h4("Title"),
      p("Subtitle",
        br(),"Line1",
        br(),"Line2",
        br(),"Line3"),

      downloadButton("Download Metadata", label = "Download")
    )
  )

server <- function(input, output, session){

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

感谢您的帮助

【问题讨论】:

    标签: r shiny shiny-server shinydashboard


    【解决方案1】:

    您不能像这样编写显示在您的页面上的文本。您可以下载存储为数据或用户输入的文本。您的代码中也存在一些问题:

    • 数据未定义,因此您未指定应下载的内容
    • write.txt 不是函数,请改用 write.table
    • downloadbutton 和 downloadHandler 应该有相同的 id。

    工作示例

    library(shiny)
    
    text=c("Line1", "Line2","Line3")
    
    ui <- fluidPage(
    
      sidebarPanel(
        h4("Title"),
        p("Subtitle",
          br(),text[1],
          br(),text[2],
          br(),text[3]),
    
        downloadButton("download_button", label = "Download")
      )
    )
    
    server <- function(input, output, session){
    
      output$download_button <- downloadHandler(
        filename = function(){
          paste("data-", Sys.Date(), ".txt", sep = "")
        },
        content = function(file) {
          writeLines(paste(text, collapse = ", "), file)
          # write.table(paste(text,collapse=", "), file,col.names=FALSE)
        }
      )
    }
    
    shinyApp(ui,server)
    

    【讨论】:

    • 这个方法的问题是它会输出引号和任何转义;也就是说,它将文本逐字写入文件。假设 R 有一个字符串test &lt;- "this is a \"test\""。使用此方法可以保留前面和结尾的引号以及转义符。有没有办法不这样做?
    • 啊。将write.table(paste(text,collapse=", "), file,col.names=FALSE) 替换为writeLines(paste(text, collapse = ", "), file)
    • @MarkWhite 我认为writeLines 是一个更好的解决方案,感谢您的反馈。我已经相应地更新了答案。
    猜你喜欢
    • 2015-09-06
    • 2013-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-20
    • 2021-09-03
    • 1970-01-01
    相关资源
    最近更新 更多