簡體   English   中英

在 shiny 應用程序中,如何讓用戶選擇要使用 write.table 下載的文件名和目錄

[英]In a shiny app how can I let the user choose the filename and directory to download with write.table

這是對此的后續問題

現在我以某種方式設法將反應 dataframe 下載到我的硬盤驅動器(!不是服務器或工作目錄)和 append 每個新條目作為write.table的新行。

有趣的是write.csv不起作用,因為它不允許append參數https://stat.ethz.ch/pipermail/r-help/2016-August/441011.html

有了這個最小的工作應用程序,我想知道如何讓用戶選擇一個目錄和一個文件名來下載。 現在我有了這個絕對路徑: file = "C:/Users/yourname/Downloads/my_df.csv"有效。 但我不知道它是否適用於其他用戶!

library(shiny)
library(shinyWidgets)

ui <- fluidPage(
  sidebarLayout(
    
    sidebarPanel(width = 4,
                 sliderInput("a", "A", min = 0, max = 3, value = 0, width = "250px"),
                 actionButton("submit", "Submit")
                 ),
    
    mainPanel(
      titlePanel("Sliders"),
      tableOutput("values")
    )
  )
)
server <- function(input, output, session) {
 
  sliderValues <- reactive({
    data.frame(Name = c("A"), Value = as.character(c(input$a)), stringsAsFactors = FALSE)
  })
  
  output$values <- renderTable({
    sliderValues()
  }) 
  
  # Save the values to a CSV file on the hard disk ----
  saveData <- reactive({write.table(sliderValues(), file = "C:/Users/yourname/Downloads/my_df.csv", col.names=!file.exists("C:/Users/yourname/Downloads/my_df.csv"), append = TRUE) })
  
  observeEvent(input$submit, {
    saveData()
  })
}
shinyApp(ui, server)

要求是用戶應該看到一個模態對話框 ui,其中包含問題“您要下載哪個文件夾和哪個文件名?”。 如果我們從 inte.net 下載,就像我們每天做的事情一樣。

我現在這樣解決了:

我意識到我有兩個選擇:

  1. 正如@Stéphane Laurent 使用downloadhandler所建議的
  2. 使用DT::datatable()

我決定使用數字 2。非常感謝您的所有投入!

library(shiny)
library(shinyWidgets)
library(DT)

ui <- fluidPage(
  sliderInput("a", "A", min = 0, max = 3, value = 0, width = "250px"),
  titlePanel("Sliders"),
  dataTableOutput("sliderValues", width="450px")
)
server <- function(input, output, session) {
  
  sliderValues <- reactive({
    df <- data.frame(
      Name = "A", 
      Value = as.character(c(input$a)), 
      stringsAsFactors = FALSE) %>% 
      pivot_wider(names_from = Name, values_from = Value)
    
    return(df)
  })

  
  # Show the values in an HTML table in a wider format----
  output$sliderValues <- DT::renderDataTable({
    DT::datatable(sliderValues(),
                  extensions = c('Buttons'),
                  options = list(
                    dom = 'frtBip',
                    buttons = list(list(extend = 'excel', filename = paste0("myname-", Sys.Date())))
                  )
    )
  })

}
shinyApp(ui, server)

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM