Search code examples
rshinyshinyappsshiny-reactivity

List and load files in Shiny


I'm new to Shiny and i'm really stuck! I'm trying to build an app where users can select a file from a list of files in a folder and simply load and display it. I've looked at similar questions but I really can't understand why my code does not work. I don't get any error msg, the output panel just stays blank..

Any help much appreciated thank you

Best Regards

library(shiny)
fpath <- "/dbfs/May2022"
ui <-   fluidPage(
  sidebarPanel(
selectInput('selectfile','Select File',choice = list.files(fpath)),
textOutput('fileselected'),
  mainPanel("Main Panel",dataTableOutput("txtout"),style = "font-size:100%") # mainPanel
)

server <- function(input,output)
{reactive({
  fullpath <- file.path(fpath,input$selectfile)
  req(fullpath)
    df <- read.csv(fullpath, header = TRUE,  sep = ",")})
  output$fileselected <- renderText({
    paste0('You have selected: ', input$selectfile)
  })
 req(df)
  output$txtout <- renderDataTable(
          head(df), options =list(pageLength = 5))
  }

shinyApp(ui,server)

Solution

  • Okay, I think below should work:

    library(shiny)
    fpath <- "/dbfs/May2022"
    ui <-   fluidPage(
      sidebarPanel(
        selectInput('selectfile','Select File',choice = list.files(fpath)),
        textOutput('fileselected'),
        mainPanel("Main Panel",dataTableOutput("txtout"),style = "font-size:100%") # mainPanel
      )
    )#Added a missing parenthesis
      
      server <- function(input,output, session) {#I added session, just because I always see it there, don't really know if it's needed
        # Also, I moved the brackets from around reactive to up to the server
        output$fileselected<-renderText({
          paste0('You have selected: ', input$selectfile)
        })
        
      # reactive({#I was told it's not a good idea to put outputs within reactives, so I blocked this out
        # fullpath <- file.path(fpath,input$selectfile)
        # req(fullpath)
        # df <- read.csv(fullpath, header = TRUE,  sep = ",")})
        # output$fileselected <- renderText({
        #   paste0('You have selected: ', input$selectfile)
        # })
        # req(df)
        output$txtout <- renderDataTable({
          req(input$selectfile)
          fullpath <- file.path(fpath,input$selectfile)
          df <- read.csv(fullpath, header = TRUE,  sep = ",")
          head(df)
          }, options =list(pageLength = 5))
      }
      
      shinyApp(ui,server)
    

    I put some comments in the code itself where I added a parenthesis and moved a bracket. The biggest thing I did though was just get rid of the reactive. I used one output for the input$fileselected, to state which file is chosen, and then the second one, output$txtout is where the data is read in and displayed. Hopefully this helps and makes sense!