Home > Enterprise >  How can I import certain file types in R
How can I import certain file types in R

Time:07-07

Sorry for what seems like a basic question, I'm very new to R and programming in general. I want to be able to determine what file type was picked from a file. For example, in this code I need to have two separate buttons for importing a CSV or excel file:

observeEvent(input$CSV, {
    Table <- read.table(file.choose(), header=TRUE, sep=",")
      output$ImportedTable <- DT::renderDataTable(Table)
  })
 observeEvent(input$Excel, {
    Table <- read_excel(file.choose())
      output$ImportedTable <- DT::renderDataTable(Table)
  })

(input$Excel/CSV is the output of an actionButton in the main pannel)

Ideally, I'd like to only require one button instead of two, and have the program able to determine what file type was chosen, and import it accordingly. and ideally, I'd like to be able to sort what data types are available to choose from when importing, since currently it allows the user to pick all file types, instead of just ones in a table format. I'd appreciate any help, thanks!

CodePudding user response:

You seem to work with shiny (this is an important bit of information missing from your main post).

In shiny you can use fileInput to restrict the format of input files. Here is a minimal reproducible example.

library(shiny)

ui <- fluidPage(
    fileInput(inputId = "file_csv", label = "CSV file", accept = ".csv"),
    fileInput(inputId = "file_xlsx", label = "XLSX file", accept = ".xlsx"),
)

server <- function(input, output) {
}

shinyApp(ui = ui, server = server)

Note that you can see the effect of accept when opening the app in your browser of choice. RStudio's native app window or Viewer Pane does not seem to respect the accept argument.

  •  Tags:  
  • r
  • Related