John Doe
John Doe

Reputation: 222

downloadHandler not producing the desired output

I've been trying for a few days to develop an app for studying purposes and I have asked a lot of questions in SO in the process. The most recent one was this and it helped develop the code that I have now.

Now I'm trying to produce a download button (using part of an example from datacamp.com) for the app and I'm not obtaining the desired output. The new adaptations are (i) adding a selection for the file extension (e.g. csv or tsv) and (ii) a download button in the body of the app in order to download a dataset as selected by the inputs in the sidebar.

I understand that RStudio browser has problems with a download button, so I'm running the app on chrome. Still my download file is neither a csv or a tsv nor it shows any resemblance with a dataset when a I try to open it (it opens as a HTML file in my machine).

I believe I might be having problems with the reactives on the server or the created function to deal with multiple menu items(convertMenuItem)* in the sidebar might not be working with the addition of a download option.

*I need to understand it more carefully. BTW, I thank @phalteman. The function was really helpful.

SUMMARY: the download output is not the desired one, but an html file. Instead I want the option to select the file type (e.g. csv or tsv) and download a dataset accordingly with the selected inputs in the sidebar. For now, it does not seem to work.

Here it is the code that I'm trying to debug:

library(shiny)
library(ggplot2)
library(dplyr)
library(shinydashboard)

rm(list=ls()); gc()

#function to adaptate menuItem

convertMenuItem <- function(mi,tabName) {
  mi$children[[1]]$attribs['data-toggle']="tab"
  mi$children[[1]]$attribs['data-value'] = tabName
  mi
}

#functions to order the plot

reorder_within <- function(x, by, within, fun = mean, sep = "___", ...) {
  new_x <- paste(x, within, sep = sep)
  stats::reorder(new_x, by, FUN = fun)
}

scale_x_reordered <- function(..., sep = "___") {
  reg <- paste0(sep, ".+$")
  ggplot2::scale_x_discrete(labels = function(x) gsub(reg, "", x), ...)
}

#example data

sample_data = data.frame(Company_Name=c("Company 1","Company 2","Company 3",
                                        "Company 1","Company 2","Company 3",
                                        "Company 1","Company 2","Company 3"),
                         Profits_MM = c(20,100,80,
                                        45,120,70,
                                        50,110,130),
                         Sales_MM = c(200,800,520,
                                      300,1000,630,
                                      410,1150,1200),
                         Year=c(2016,2016,2016,
                                2017,2017,2017,
                                2018,2018,2018))

###app code###

# UI
ui <- dashboardPage(
  dashboardHeader(title = "Dashboard Test"),
  dashboardSidebar(
    sidebarMenu(
      convertMenuItem(menuItem("Data Selection", tabName = "dc", icon = icon("dashboard"),
                               checkboxGroupInput(inputId = "sel_com",
                                                  label = "Company Selection:",
                                                  choices = c("Company 1","Company 2","Company 3"),
                                                  selected = "Company 1"),
                               selectInput(inputId = "y", 
                                           label = "Performance Variable",
                                           choices = c("Profits (in Millions)" = "Profits_MM", 
                                                       "Sales (in Millions)" = "Sales_MM"),
                                           selected = "Profits_MM"),
                               sliderInput("year","Year Selection:",
                                           min=2016,
                                           max=2018,
                                           value=c(2017,2018),
                                           step=1),
                               radioButtons(inputId = "filetype",
                                            label = "Select filetype:",
                                            choices = c("csv", "tsv"),
                                            selected = "csv")), tabName="dc")
    )
  ),  

 dashboardBody(

  tabItems(
    # First tab content
    tabItem(tabName = "dc",

            fluidRow(column(width=12,box(plotOutput("barplot"))),
             downloadButton(outputId = "download_data", 
                            label = "Download data")


              )
      )
    )
  )
)


# Server
server <- function(input, output, session) {

  companies_sel <- reactive({

    req(input$sel_com)

    sample_data_gg = filter(sample_data, Company_Name %in% input$sel_com)
    #  print(sample_data_gg)
    sample_data_gg

  })

  year_sample <- reactive({

    req(input$year)
    sample_data_gg = sample_data
    if((input$year[2] - input$year[1])>1){

      Years = seq(input$year[1],input$year[2])

      sample_data_gg = filter(companies_sel(), Year %in% Years)

    }  

    if((input$year[2] - input$year[1])==1){

      sample_data_gg = filter(companies_sel(), Year %in% input$year)

    }
    #  print(sample_data_gg)
    sample_data_gg
  })


  output$barplot = renderPlot({

    sample_data_gg = year_sample()

    y <- input$y
    ggplot(data = sample_data_gg, aes(x=reorder_within(Company_Name, get( y ), Year), y = get( y ))) +
      geom_col(position="dodge", fill="darkred") +
      facet_wrap(Year~., scales = "free")  +
      scale_x_reordered() +
      theme(axis.text.x = element_text(angle = 60, hjust = 1))


  })

  # Download file as written in a datacamp example
  output$download = downloadHandler(filename = 
                                       function(){paste("company_obs", input$filetype, sep=".")},
                                    content = function(file) { 
                                       if(input$filetype == "csv"){ 
                                         write_csv(year_sample(), path = file) 
                                       }
                                       if(input$filetype == "tsv"){ 
                                         write_tsv(year_sample(), path = file) 
                                       }
                                     }
  )

}

app = shinyApp(ui, server)

runApp(app, launch.browser = TRUE)  

Upvotes: 0

Views: 1287

Answers (1)

phalteman
phalteman

Reputation: 3532

Simple fix for this one. Your downloadButton id is download_data, but you reference output$download in the downloadHandler. Change it to output$download_data and you should be good. You'll also need to include the readr library up front, since write_csv() and write_tsv() are from that package.

Upvotes: 3

Related Questions