我正在尝试使用R shiny中的renderTable函数生成一个表,然后使用downloadHandler函数将该表/ data.frame下载为csv文件。不知怎的,我不断收到以下错误:
下载过程中出错: 下载http://127:0:0.1:3001/session/时出错 0303bd426fce88837ae277aa3b406dd / download / downloadData?w = - 服务器 回复:内部服务器错误
下面是一个示例代码,我生成一个简单的数据框并尝试使用downloadHander下载它:
library(shiny)
# Define UI for data download app ----
ui <- fluidPage(
# App title ----
titlePanel("Downloading Data"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Button
downloadButton("downloadData", "Download")
),
# Main panel for displaying outputs ----
mainPanel(
tableOutput("table")
)
)
)
# Define server logic to display and download selected file ----
server <- function(input, output) {
# Table of selected dataset ----
output$table <- renderTable({
data.frame(a =c(1,2,3),b=c("q","s","f"))
})
# Downloadable csv of selected dataset ----
output$downloadData <- downloadHandler(
filename = function() {
paste("test.csv")
},
content = function(file) {
write.csv(output$table, file, row.names = FALSE)
}
)
}
shinyApp(ui,server)
答案 0 :(得分:1)
这里需要做一些事情:
reactive
表达式。reactive
表达式,就可以轻松下载数据。
尝试以下操作:
library(shiny)
ui <- fluidPage(
titlePanel("Downloading Data"),
sidebarLayout(
sidebarPanel(downloadButton("downloadData", "Download")),
mainPanel(tableOutput("table"))
)
)
server <- function(input, output) {
data <- shiny::reactive(data.frame(a = c(1, 2, 3), b = c("q", "s", "f")))
output$table <- renderTable(data())
output$downloadData <- downloadHandler(
filename = function() {
paste("test.csv")
},
content = function(file) {
write.csv(data(), file, row.names = FALSE)
}
)
}
shinyApp(ui,server)
答案 1 :(得分:0)
您无法导出renderTable {},因为这会将许多元素放入HTML中, 您需要先保存进入表中的数据并将其导出 seperately。
dataTable<-data.frame(a =c(1,2,3),b=c("q","s","f"))
output$downloadData <- downloadHandler(
filename = function() {
('test.csv')
},
content = function(con) {
write.table(dataTable,row.names = FALSE,col.names=T, sep=",",con)
},
contentType="csv"
)