R shiny to download xlsx file. Error!

Hello!

I am a student and I have an assignment that is due in couple of days :c I am trying to run an app on shiny to make an interactive chart (selecting date range) for two variables and it is giving me different errors.
The problem appears when I try to download the data. If I run the app without the code to download, it runs perfectly. But when I add the code to download the data in xlsx the error that appears is:

Error in parse(file, keep.source = FALSE, srcfile = src, encoding = enc) :
C:\Users\paola\OneDrive\Documentos\8 vo\Administracion financiera internacional\AplicacionesShiny\prueba/server.R:5:57: unexpected symbol
4: output$distPlot <- renderPlot({
5: if(input$country == "México"){library("siebanxicor")library
^
Warning: Error in sourceUTF8: Error sourcing C:\Users\paola\AppData\Local\Temp\Rtmp0GgXo8\filea6426655e40
1: runApp
Error in sourceUTF8(serverR, envir = new.env(parent = sharedEnv)) :
Error sourcing C:\Users\paola\AppData\Local\Temp\Rtmp0GgXo8\filea6426655e40

And other thing is that I tried to run the code to download the data en .csv and it did download the data if I run the app in R studio. But when I publish the app, the data are not in .csv and a can't open the file in Excel :c.
Hope someone can help me. Thanks!

library(shiny)
# Define UI ----
ui <- fluidPage(
  
  # App title ----
  # titlePanel("México"),
  
  # Sidebar layout with input and output definitions ----
  sidebarLayout(
    
    # Sidebar panel for inputs ----
    sidebarPanel(
      # Country Options
      selectInput("country", "País:",
                  c("México",
                    "EE.UU")),
      
      # Input: Slider for the number of bins ----
      dateRangeInput("daterange", "Rango de Datos:",
                     start = "2001-01-01",
                     end   = "2010-12-31",format = "yyyy-mm-dd",startview = "month",separator = " a "), 
      h5("Inflación Máxima:"),verbatimTextOutput("infmax"),h5("Fecha Inflación Máxima:"), verbatimTextOutput("fechainfmax"),h5("Inflación Mínima:"),verbatimTextOutput("infmin"), h5("Fecha Inflación Mínima:"), verbatimTextOutput("fechainfmin"),
      helpText("Nota: Añadir '.csv' al guardar el archivo en la ubicación deseada."),
      downloadButton("downloadData", "Descargar")),
    
    # Main panel for displaying outputs ----
    mainPanel(
      
      # Output: Plot ----
      plotOutput(outputId = "distPlot"),
      tableOutput("view")
      
    )
  )
)

# Define server logic ----
server <- function(input, output) 
{ 
  output$distPlot <- renderPlot({
    if(input$country == "México"){library("siebanxicor")
      library(writexl)
      setToken("0358b331500d7980c8e3e9f9ca474064aa0c68f12be093197121da713701a5a9")
      idSeries<-c("SP30578")
      series<-getSeriesData(idSeries,input$daterange[1],input$daterange[2])
      data<-getSerieDataFrame(series,"SP30578")
      data1<-data[order(data[,2],decreasing=FALSE),]
      data1<-cbind(as.character(data1[,1]),data1[,2])
      colnames(data1)<-c("Fecha","Inflación México")
      plot(data,pch=".",type="l",main="Anual (mes vs. mes)",xlab="Fecha",ylab="%")
      
      infmin<-head(data1[,2],1)
      infmax<-tail(data1[,2],1)
      fechainfmin<-head(data1[,1],1)
      fechainfmax<-tail(data1[,1],1)
      
      output$infmax<-renderPrint({infmax})
      output$fechainfmax<-renderPrint({fechainfmax})
      
      output$infmin<-renderPrint({infmin})
      output$fechainfmin<-renderPrint({fechainfmin})
      output$view<-renderTable({head(data1,n=5)})
      
      # Reactive value for selected dataset ----
      datasetInput <- reactive({
        data
      })
      # Table of selected dataset ----
      output$table <- renderTable({
        datasetInput()
      })
      # Downloadable csv of selected dataset ----
      output$downloadData <- downloadHandler(
        filename = function() {"ae.xlsx"},
        content = function(file) {write_xlsx(datasetInput(), path = file, row.names = TRUE)
        }
      )
    }
    else{
      library(fredr)
      fredr_set_key("540b061c529e940bc8f16226de28fa79")
      api_key<-fredr_get_key()
      data<-fredr(series_id="MEDCPIM158SFRBCLE",frequency="m",observation_start=as.Date(input$daterange[1]),observation_end=as.Date(input$daterange[2]))
      data<-cbind(data[,1],data[,3])
      data1<-data[order(data[,2],decreasing=FALSE),]
      data1 <- cbind(as.character(data1[,1]), data1[,2]) #para modificar fecha en EE.UU
      colnames(data1)<-c("Fecha","Inflación EE.UU")
      plot(data,pch=".",type="l",main="Annual (month vs. month)",xlab="Fecha",ylab="%")
      
      infmin<-head(data1[,2],1)
      infmax<-tail(data1[,2],1)
      fechainfmin<-head(data1[,1],1)
      fechainfmax<-tail(data1[,1],1)
      
      output$infmax<-renderPrint({infmax})
      output$fechainfmax<-renderPrint({fechainfmax})
      
      output$infmin<-renderPrint({infmin})
      output$fechainfmin<-renderPrint({fechainfmin})
      output$view<-renderTable({head(data1,n=5)})
      # Reactive value for selected dataset ----
      datasetInput <- reactive({
        data
      })
      # Table of selected dataset ----
      output$table <- renderTable({
        datasetInput()
      })
      # Downloadable csv of selected dataset ----
      output$downloadData <- downloadHandler(
        filename = function() {
          paste(input$dataset, ".csv", sep = "")
        },
        content = function(file) {
          write.csv(datasetInput(), file, row.names = TRUE)
        }
      )
    }
    
  })}

# Run the app ----
shinyApp(ui = ui, server = server)

My advice is to restructure your app, so that it does not nest.
your app is currently structured as the the server part defines a single output$distPlot / render function that does all the server logic. This is a bad idea, and shiny apps are not intended to be written in such a way.
the server code should provide definitions of all the output$ / render funcs individually, if they need to be driven by common elements, chunck of reactive data, these should be explicitly defined and referred to by name.

However, you say that your app works aside from the download, so perhaps you can 'get away with' less than ideal structuring of code... maybe you have not saved the R scripts in UTF-8; try the save with encoding then UTF-8 option in the file menu for each of your scripts.

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.