gpt4 book ai didi

r - 如何在 Shiny 的模块中使用 downloadButton 和 downloadHandler

转载 作者:行者123 更新时间:2023-12-05 03:32:21 36 4
gpt4 key购买 nike

我正在尝试构建一个 Shiny 的模块,我可以使用它从 Shiny 的应用程序下载不同的文件。但是 downloadButton 没有像我希望的那样工作。它正在响应一个不是我想要的 html 文件。这是我的代码:

library(shiny)

downloadUI <- function(id, label){
ns <- NS(id)

actionButton(
inputId = ns("action"),
label = label,
icon = icon("download")
)
}

downloadServer <- function(id, filename){
moduleServer(
id,
function(input, output, session){
observeEvent(
input$action,
{
showModal(
modalDialog(
title = NULL,
h3("Download the file?", style = "text-align: center;"),
footer = tagList(
downloadButton(
outputId = "download",
label = "Yes"
),
modalButton("Cancel")
),
size = "m"
)
)
}
)

output$download <- downloadHandler(
filename = paste0(filename, ".csv"),
content = function(file){
write.csv(iris, file = file, row.names = FALSE)
}
)
}
)
}

ui <- fluidPage(
downloadUI("irisDownload", label = "Download Iris data")
)

server <- function(input, output, session) {
downloadServer("irisDownload", filename = "iris")
}

shinyApp(ui, server)

谁能帮助我理解我在这里做错了什么?

最佳答案

您只需要在服务器端为 downloadButton 命名空间 ns。试试这个

library(shiny)

downloadUI <- function(id, label){
ns <- NS(id)

actionButton(
inputId = ns("action"),
label = label,
icon = icon("download")
)
}

downloadServer <- function(id, filename){
moduleServer(
id,
function(input, output, session){
ns <- session$ns
observeEvent(
input$action,
{
showModal(
modalDialog(
title = NULL,
h3("Download the file?", style = "text-align: center;"),
footer = tagList(
downloadButton(
outputId = ns("download"),
label = "Yes"
),
modalButton("Cancel")
),
size = "m"
)
)
}
)

output$download <- downloadHandler(
filename = paste0(filename, ".csv"),
content = function(file){
write.csv(iris, file = file, row.names = FALSE)
}
)
}
)
}

ui <- fluidPage(
downloadUI("irisDownload", label = "Download Iris data")
)

server <- function(input, output, session) {
downloadServer("irisDownload", filename = "iris")
}

shinyApp(ui, server)

关于r - 如何在 Shiny 的模块中使用 downloadButton 和 downloadHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70492014/

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