我有一个允许用户上传数据的应用程序,然后有一个操作按钮来触发一些计算。然后,我有一些进度条向用户显示该过程将花费多长时间。计算完成后,我想添加一个下载按钮,以便用户可以下载计算结果。
我不确定如何访问在观察事件函数中创建的数据表,以便可以在downloadhandler函数中使用它?
这是我的代码:
server <- function(input, output) {
options(shiny.maxRequestSize=200*1024^2)
file_name <- reactive({
inFile <- input$file1
if (is.null(inFile))
return(NULL)
return (stringi::stri_extract_first(str = inFile$name, regex = ".*(?=\\.)"))
})
output$myFileName <- renderText({ paste("Claim data selected:",file_name()) })
mydata <- reactive({
inFile <- input$file1
if (is.null(inFile))
return(NULL)
tbl <- read.csv(inFile$datapath,sep=";")
return(tbl)
})
output$my_output_data <- DT::renderDataTable({
mydata() },
options = list(
lengthChange = FALSE,
autowidth = TRUE,
columnDefs = list(list(width = '70%', targets = 1)))
)
output$summary <- renderText({
dt.size <- nrow({mydata()})
paste("There are",dt.size,"records.", sep =" ")
})
observeEvent(input$goButton1,{
output$table1 <- DT::renderDataTable({
withProgress(message = 'Calculation in progress...',
value = 0, {function1({mydata()},progress=TRUE)})
})
output$table1 <- DT::renderDataTable(function1({mydata()}))
output$downloadData <- downloadHandler(
filename = function() {
paste("DLR result-", Sys.Date(), ".csv", sep="")
},
content = function(file) {
#fwrite("output$table 1 should be here", file)
})
})
}
答案 0 :(得分:0)
给定代码的问题是data.table库中的fread
函数采用了data.frame或data.table参数。在这里,您给了它一个DT
javascript DataTable对象。我的代码使用基本R data.frames而不是data.table,但是您应该能够对其进行相应的调整。
library(shiny)
library(shinydashboard)
ui = dashboardPage(
dashboardHeader(title = "File Download"),
dashboardSidebar(),
dashboardBody(
fluidPage(
fluidRow(
box(width=12,
title = "UploadDownload",
fileInput("file1", label="File1 upload"),
downloadButton("downloadData", "Download")
)
),
fluidRow(
box(width=12,
title = "DataTable",
textOutput("myFileName"),
DT::dataTableOutput("my_output_data")
)
)
)
)
)
server = function(input, output) {
file_name = reactive({
req(input$file1)
return(gsub("\\..*$", "", input$file1$name))
})
output$myFileName = renderText({
paste("Claim data selected:",file_name())
})
mydata = reactive ({
req(input$file1)
tbl = read.csv(input$file1$datapath)
return(tbl)
})
mydata2 = reactive ({
tbl = mydata()
# a calculation that will take some time
withProgress(message="Adding another column", detail="this may take some time",
{
n = dim(tbl)[2]
tbl$newcolumn = NULL
for (i in 1:n) {
tbl$newcolumn[i] = sample.int(10,1)
incProgress(1/n)
Sys.sleep(5/n)
}
})
})
output$my_output_data = DT::renderDataTable(
mydata(),
options = list(
lengthChange=FALSE,
autowidth=TRUE,
columnDefs=list(list(width='70%', targets=1))
)
)
output$downloadData = downloadHandler(
filename = function() {
paste("DLR results-", Sys.Date(), ".csv", sep="")
},
content = function(file) {
write.csv(mydata2(), file)
}
)
}
shinyApp(ui, server)