创建可以输出多种文件类型R Shiny的downloadButton
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了创建可以输出多种文件类型R Shiny的downloadButton相关的知识,希望对你有一定的参考价值。
我为R Shiny应用程序创建了一个输出CSV的下载按钮。我想在UI中添加复选框,以获取输出json,xls和TSV文件的选项,然后输出服务器函数中的相应函数。任何见解?贝娄是一些与此相关的最小代码:
library(shiny)
set.seed(123)
N<- 500
M<-56
EF<- matrix( rnorm(N*M,mean=23,sd=3), N, M)
WM<- matrix( rnorm(N*M,mean=20,sd=3), N, M)
DP<- matrix( rnorm(N*M,mean=25,sd=3), N, M)
Date <- seq(as.Date("2018-01-01"), as.Date("2018-02-25"), by="days")
Date <- as.POSIXct(Date, format = "%Y-%m-%d %H:%M")
ui <- fluidPage(
titlePanel(code(strong("Measures"), style = "color:black")),
sidebarLayout(
sidebarPanel(
strong("Tools:"),
selectInput("Test",
label = "Choose a measure to display",
choices = c("EF",
"WM",
"DP"
),
selected = "EF"),
downloadButton("downloadData", "Download")),
mainPanel(
code(strong("Output Data"))
))
)
server <- function(input, output) {
output$downloadData <- downloadHandler(
filename = function() {
paste(input$dataset, "Table.csv", sep = ",")
},
content = function(file) {
write.csv(x, file, row.names = FALSE)
}
)
}
# Run that shit ----
shinyApp(ui = ui, server = server)
答案
不是最优雅,但这是一个选择。我创建了一个模拟示例 - 我无法使用您的代码,因为x
(您正在下载的内容)未在您的示例中定义。
library(shiny)
library(RJSONIO)
library(xlsx)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("dataset",
label = "Choose dataset",
choices = c("iris", "cars")),
radioButtons("downloadType", "Download Type",
choices = c("CSV" = ".csv",
"JSON" = ".json",
"XLS" = ".xls",
"TSV" = ".tsv"),
inline = TRUE),
downloadButton("downloadData", "Download")
),
mainPanel()
)
)
server <- function(input, output) {
datasetInput <- reactive({
switch(input$dataset,
"iris" = iris,
"cars" = cars)
})
output$downloadData <- downloadHandler(
filename = function() {
paste0(input$dataset, "_Table", input$downloadType)
},
content = function(file) {
if(input$downloadType == ".csv") {
write.csv(datasetInput(), file, row.names = FALSE)
} else if(input$downloadType == ".json") {
exportJSON <- toJSON(datasetInput())
write(exportJSON, file)
} else if(input$downloadType == ".xls") {
write.xlsx(datasetInput(), file,
sheetName = "Sheet1", row.names = FALSE)
} else if(input$downloadType == ".tsv") {
write.table(datasetInput(), file, quote = FALSE,
sep=' ', row.names = FALSE)
}
}
)
}
shinyApp(ui = ui, server = server)
以上是关于创建可以输出多种文件类型R Shiny的downloadButton的主要内容,如果未能解决你的问题,请参考以下文章
如何使用具有多个输出的 R Shiny moduleServer
使用inputBox的输出作为R Shiny中inputSlider的输入