I am trying to download a datatable using modified data from Shiny to a csv. The app runs, I can upload my data, and the datatable is created, but when I try to download it, it does not download as a csv. There is a file that downloads but it has no file format listed and can't be opened. Is there something wrong with my download related code?
Download code in server.R
server <- function(input, output, session) {
observe({
file1=input$file1
if (is.null(file1)){
return(NULL)
}
df<-read.csv(file1$datapath, fileEncoding = "UTF-8-BOM")
df$FAIL<-ifelse(df$OPERATION_STATUS %in% "FAIL",1,0)
setDT(a)
a[,group_i := as.Date(DATE) >= Sys.Date()-30]
dt<-(a[, .(
"Overall Percent" = round(sum(OPERATION_STATUS == "FAIL") / .N * 100, 2),
"30 Day Percent" = round(sum(OPERATION_STATUS[group_i] == "FAIL") / sum(group_i) * 100, 2),
"Percent Change" = round((sum(OPERATION_STATUS[group_i] == "FAIL")/sum(group_i) / (sum(OPERATION_STATUS == "FAIL")/.N)*100), 2)),
keyby = .("Area" = CRIT_CODE)])
output$tab<-DT::renderDataTable({
datatable(dt, options=list(pagelength=30, lengthMenu=c(30,50)), rownames=FALSE, server=FALSE) %>%
formatStyle("Percent Change", color=styleInterval(100, c("black","red")))
})
output$dltab<-downloadHandler(
filename=function(){
paste("Fail Rate Summary-", Sys.Date(), ".csv", sep="")},
content=function(file){
write.csv(dt, file)
}
)
Download Button Statement in ui.R
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose CSV File",
accept=".csv"),
width=3
),
mainPanel(
tabsetPanel(
tabPanel(
"Percent Fails",
DT::dataTableOutput("tab"),
downloadButton("dltab", "Download"))
))))
Sample Data
n <- 60
set.seed(21)
a <- data.frame(
DATE =
rev(seq.Date(as.Date("2018-01-01"), as.Date("2018-06-15"), "days"))[1:n],
OPERATION_STATUS = sample(c("PASS","FAIL"), n, replace = TRUE),
CRIT_CODE = sample(c("A", "B", "C"), n, replace = TRUE)
)
})
}