Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use shinyFileChoose to create an reactive object to load a data.frame

I've been using fileInput in my shiny app to upload a file and then create a reactive object that allow me to read the data.frame and do another stuff like subsetting or filtering. However, I need to get the absolute path of the file for another calculations, and it seems that fileUpload only stores a temporal path.

Here is the server part that works

 server = function(input, output) {
 options(shiny.maxRequestSize=100*1024^2)

 contents <- reactive({
     inputFile <- input$fileUpload
     if (is.null(inputFile))
     return()
     read.delim(inputFile$datapath, header = TRUE)
 })

 # Return filename as another object
 file_name <- reactive({
      inFile <- input$fileUpload
      if (is.null(inFile))
      return()
      else {  print(inFile$name); return(tools::file_path_sans_ext(inFile$name))}
  })  

output$tabla <- DT::renderDataTable({
if(is.null(contents()))
  return()
  DT::datatable(contents(), 
              filter = 'top')
})

However, I would like to use the shinyFiles option because it stores the real path, and I will need that path to load more files I have tries this part of code in the server to mimic the same behaviour that fileUpload but it does not work

server = function(input, output, session) {

volumes = getVolumes()
volumes <- c(Home = fs::path_home(), "R Installation" = R.home(), getVolumes()())

file_selected <- reactive({
   shinyFileChoose(input, "file", roots = volumes, session = session)
   return(parseFilePaths(volumes, input$file))
})

contents <- reactive({
  if (is.null(file_selected()))
  return()
  read.delim(file_selected(), header = TRUE)
})

# Reactive function creating the DT output object
 output$tabla <- DT::renderDataTable({
  if(is.null(contents()))
   return()
   DT::datatable(contents(), 
              filter = 'top')
 })

I got an error about file must be a character string or connection and if I use read.delim(as.character(file_selected()), header = TRUE) then the error is about invalid "description" argument

like image 215
user2380782 Avatar asked Oct 16 '22 09:10

user2380782


1 Answers

There are different possible causes of the error. Try the following steps:

  • Use req(input$file) before parsing the file paths
  • Check if input$file is NULL before parsing the file paths
  • Return $datapath of the parseFilePaths function.

According to this, your code should look like the following:

file_selected <- reactive({
   shinyFileChoose(input, "file", roots = volumes, session = session)
   req(input$file)
   if (is.null(input$file))
      return(NULL)    
   return(parseFilePaths(volumes, input$file)$datapath)
})

Hope it works for you.

like image 83
Taher A. Ghaleb Avatar answered Nov 01 '22 16:11

Taher A. Ghaleb