我已经简化了很多我要构建的闪亮应用程序,但是,在这个想法中,我有两个功能:
choose_input <- function(n1,n2,n3){
x1 <<- n1+n2
x2 <<- n2+n3
x3 <<- (n1*n2)/n3
}
createmydata <- function(n){
c1 <- c(1:n)
c2 <- c1+(x2*x3)
c3 <- c2+x1
df <- data.frame("column1"=c1,"column2"=c2,"column3"=c3)
return(df)
}
您会告诉我,我可以用这两个功能执行一个功能,因为它们非常简单,但是在我的应用程序中,有很多行,我必须将两者分开。无论如何,这是我的模拟代码:
ui <- fluidPage(
numericInput("n1",label="Choose the first parameter",min=0,max=100,value=3),
numericInput("n2",label="Choose the second parameter",min=0,max=100,value=4),
numericInput("n3",label="Choose the third parameter",min=0,max=100,value=5),
numericInput("n",label="Choose dataframe length",min=1,max=10000,value=100),
radioButtons("filetype", "File type:",
choices = c("csv", "tsv")),
downloadButton('downloadData', 'Download'),
tableOutput("data")
)
server <- function(input,output){
RE <- reactive({
choose_input(input$n1,input$n2,input$n3)
createmydata(input$n)
})
output$data <- renderTable({
RE()
})
output$downloadData <- downloadHandler(
filename = function() {
paste(name, input$filetype, sep = ".")
},
content = function(file) {
sep <- switch(input$filetype, "csv" = ",", "tsv" = "t")
write.table(RE(), file, sep = sep,
row.names = FALSE)
}
)
}
shinyApp(ui = ui, server=server)
如您所见,我想将输出表下载到CSV或Excel文件...我让您尝试代码,然后尝试单击下载按钮,它不起作用...
调试
当我在上面运行代码并尝试下载数据集时,我在rstudio中的控制台窗格中收到了以下警告和错误消息。
Warning: Error in paste: object 'name' not found
Stack trace (innermost first):
1: runApp
Error : object 'name' not found
这使我检查了shiny::downloadHandler()
中filename
参数中使用的paste()
函数。在代码中,您使用对象name
而不为其分配值。
我在downloadHandler()
内的filename
参数中替换了name
。
output$downloadData <- downloadHandler(
filename = function() {
paste( "customTable", input$filetype, sep = ".")
},
content = function(file) {
sep <- switch(input$filetype, "csv" = ",", "tsv" = "t")
write.table(RE(), file, sep = sep,
row.names = FALSE)
}
)
在浏览器中下载数据
运行app.R
脚本后,我单击了Open in Browser
按钮以在Chrome上的新标签中查看Shiny应用程序。到达那里后,我成功地下载了download
按钮后成功下载.CSV和.TSV文件。
注意:我正在寻找为什么需要采取此操作的更好的理由,但是目前,我遇到了这个相关的So Post Shiny App:下载Handler不会产生文件。