RShiny and Modules output. Object of type environment is not subsettable

377 views Asked by At

Dear people of sackoverflow,

I am currently trying to create an app where a user can upload a dataset from various sources. I tried to isolate the code for the upload in a separate Shiny module. However, R throws an error saying that an environment object is not subsettable. I am fairly new to shiny so would appreciate any advice regarding the use of modules too. :)

library(shiny)

fileInputUI <- function(id){
  
  ns <- NS(id)
  
  fileInput(
    inputId = ns("file"), 
    label = "Select a file"
  )
  
}

fileInputServer <- function(id){
  
  moduleServer(id, function(input, output, session){
    
    dataset <- reactive({
      
      req(input$file)
      
      # Get file extension and datapath      
      ext <- tools::file_ext(input$file$name)
      datapath <- input$file$datapath
      
      # Need reactive values to store input data in
      read_data_options <- reactiveValues()
      
      read_data_options$sep <- NULL
      
      if(ext == "csv"){
        
        choices_sep <- c(",", ";", "", "\\t")
        names(choices_sep) <- c("Comma (,)", "Semicolon (;)", "White space ( )", "Tab separated (\\t)")
        
        showModal(
          ui = modalDialog(
            selectInput(
              inputId = NS(id, "sep"), 
              label = "Which separator is used for your data",
              choices = names(choices_sep),
              selected = ""
            ),
            # Input is required so no dismiss button
            footer = tagList(
              modalButton("Dismiss"),
              actionButton(
                inputId = NS(id, "submit_csv"), 
                label = "Submit")
            ),
            easyClose = TRUE
          )
        )
        
        # Set input value from submit button
        observeEvent(
          eventExpr = input$submit_csv, 
          handlerExpr = {
            
            
            read_data_options$sep <- choices_sep[input$sep]
            removeModal()
            
            read.csv(
              file = datapath,
              sep = read_data_options$sep
            )
          }
        )
        
      } else {
        
        NULL
        
      }
      
    })
    
    dataset
    
  })
  
}

# Shiny App
ui <- fluidPage(
  fileInputUI("test"),
  
  tableOutput("head_data")
)

server <- function(input, output, session) {
  
  dataset <- fileInputServer("test")
  
  output$head_data <- renderTable(head(dataset()))
  
}

shinyApp(ui, server)

I used modalDialog because I figured it to be the simplest approach to asking users about additional inputs to the read function for example the separator in case of read.csv or the startRow for read.xlsx etc.

Thanks for your replies

0

There are 0 answers