Search code examples
rshinyflexdashboard

R Shiny: How to read different CSV file based of user input?


I have a flexdashboard shiny app I am working on and trying to create a reactive function that imports different datasets (through read.csv()) based on the user input.

I have 2 empty csv files in a folder called "Test". One is called Oct 2021 and the other is called Nov 2021.

Rather than loading in all the csv files in - I would like the user to choose the name of the file and have it load in.

Here is my code

---
title: "Test"
output: 
  flexdashboard::flex_dashboard:
runtime: shiny
---

Page 1 
=====================================

Inputs {.sidebar}
-------------------------------------

```{r}
library(flexdashboard)
library(shiny)
library(DT)
library(readr)
```

```{r}
selectInput("input_type","Select Month:", c("Oct 2021", "Nov 2021"))
```

Column 
-----------------------------------------------------------------------

### DATA OUTPUTS HERE 

```{r}
#Prepare data here 

data <- reactive({
  tmp <- read.csv(input$input_type$"~Test/")
  tmp
})



```

```{r}

renderDataTable(
  datatable(
    data()
  )
)

```

I thought this would work but I get an error "$ operator is invalid for atomic vectors" enter image description here


Solution

  • input$input_type is the name of the file, but to specify the complete path we need to paste some strings together. read.csv can be used like this:

    read.csv(paste0('~/Test/', input$input_type, '.csv'))

    Sample Shiny App:

    library(shiny)
    library(DT)
    
    ui <- fluidPage(
      sidebarLayout(
        sidebarPanel(selectInput("input_type","Select Month:", c("Oct 2021", "Nov 2021")),
                     actionButton('load_csv', 'Load csv')),
       mainPanel(dataTableOutput('dt'))
      )
    )
    
    server <- function(input, output, session) {
      
      data <- eventReactive(input$load_csv, {
        read.csv(paste0('~/Test/', input$input_type, '.csv'))
      })
      
      output$dt <- renderDataTable({
        req(data())
        datatable(
          data()
        )}
      )
    }
    
    shinyApp(ui, server)