'How to select either the input from fileInput or textAreaInput in the server of shiny app?

I would like to put both fileInput and textAreaInput in my app but I do not know how to define them in the server. For example, when choosing fileInput consider the uploaded file, and when choosing textAreaInput consider the entered regions (sep=" |\t").

Any help would be appreciated!

This is the codes that I have tried:

ui <- fluidPage( tabPanel("Data", icon = icon("database"),
                          tabsetPanel(type = "pills",
                                      tabPanel("Data Table",icon = icon("table"),
                                               sidebarLayout(
                                                 sidebarPanel (
                                                   selectInput("choose","Choose file source",choices = c("file","text"),selected = NULL),
                                               conditionalPanel("input.choose=='file'",
                                                                fileInput("data_file", "Upload coordinates in .bed/.csv format:",multiple = TRUE,accept = c(".bed",".csv"))),
                                               conditionalPanel("input.choose=='text'",
                                                                textAreaInput("data_paste", "Enter coordinates:",placeholder =  "Paste like chr1 100 200 per line")),
                                               actionButton("run", label="Run overlap"),
                                               actionButton("add.table", "See overlap results"),
                                               downloadButton("download_res", "Download overlap results"),
                                               width = "3"),
                                               mainPanel(dataTableOutput("overlap.table"))
                                               )
                                               )
                                      )
                          )
                 )


server <- function (input, output, session) { 
  
  ## file or text condition
  user_query.data <- reactiveValues(table=NULL)
  
  observeEvent(input$data_file,{
    req(input$data_file)
    user_query.data$table <- 
      ext <- tools::file_ext(input$data_file$name)
    switch(ext,
           csv = fread(input$data_file$datapath, delim = ",",header=F) %>% 
             dplyr::rename (chr =V1, start=V2, end=V3) %>% data.table() %>% setkey(chr, start, end),
           bed = fread(input$data_file$datapath,header=F) %>% 
             dplyr::rename (chr =V1, start=V2, end=V3) %>% data.table() %>% setkey(chr, start, end),
           validate("Invalid file; Please upload a .csv or a .bed file")
           )
    })
  
  observeEvent(input$data_paste,{
    req(input$data_paste)
    user_query.data$table <- strsplit(input$data_paste," ") %>% data.table() %>% setkey(chr, start, end)
    })
  
  ## read our table
  DF<-reactive({
    data<-data.table(chr=c("chr1","chr1","chr3","chr2"),start=c(100,180,50,20),end=c(120,250,55,22))%>% setkey(chr, start, end)
    })
  
  ## Run Analyze
  analyzed <- eventReactive(input$run, {
    req(input$run)
    query_overlap<- foverlaps(data.table(user_query.data$table) ,DF (),  nomatch = 0)
    })

  shinyjs::disable("download_res")
  observeEvent(analyzed(), {
    shinyjs::enable("download_res")
    })
  output$download_res <- downloadHandler(
    filename = ".csv",
    content = function(file) {
      write.csv(analyzed(), file, row.names = FALSE)
    }
  )
  }

shinyApp(ui, server)

Update :

The below code is working well when I upload a file in bed format but it cannot recognize when I put coordinate as text in the textAreaInput.

ui <- fluidPage( tabPanel("Data", icon = icon("database"),
                          tabsetPanel(type = "pills",
                                      tabPanel("Data Table",icon = icon("table"),
                                               sidebarLayout(
                                                 sidebarPanel (
                                                   selectInput("choose","Choose file source",choices = c("file","text"),selected = NULL),
                                               conditionalPanel("input.choose=='file'",
                                                                fileInput("data_file", "Upload coordinates in .bed/.csv format:",multiple = TRUE,accept = c(".bed",".csv"))),
                                               conditionalPanel("input.choose=='text'",
                                                                textAreaInput("data_paste", "Enter coordinates:",placeholder =  "Paste like chr1 100 200 per line")),
                                               actionButton("run", label="Run overlap"),
                                               actionButton("add.table", "See overlap results"),
                                               width = "3"),
                                               mainPanel(dataTableOutput("overlap.table"))
                                               )
                                               )
                                      )
                          )
                 )


server <- function (input, output, session) { 
  ## file or text condition
  data <- reactiveVal()
  
  observeEvent(
    eventExpr = input$run,
    handlerExpr = {
      switch(input$choose,
             file = fread(input$data_file$datapath, header=F) %>%
               dplyr::rename (chr =V1, start=V2, end=V3) %>% setkey(chr, start, end),
             text = data.table(input$data_paste)%>%
               dplyr::rename (chr =V1, start=V2, end=V3) %>% setkey(chr, start, end)
      ) %>% data()
    }
  )
  
  DF<-reactive({
    df<-data.table(chr=c("chr3","chr1","chr3","chr2"),start=c(10,180,50,20),end=c(12,250,55,22))%>% setDT() %>% setkey(chr, start, end)
  })
  ## Run Analyze
  analyzed <- eventReactive(input$run, {
    req(input$run)
    query_overlap<- foverlaps(data() ,DF(),  nomatch = 0)
    })

  output$overlap.table <- renderDT(analyzed()) 

  }

shinyApp(ui, server)

And getting the below error:

Listening on http://127.0.0.1:7624
Warning: Error in : Can't rename columns that don't exist.
x Column `V2` doesn't exist.

Warning: Error in foverlaps: y and x must both be data.tables. Use 
`setDT()` to convert list/data.frames to data.tables by reference or 
as.data.table() to convert to data.tables by copying.


    


Solution 1:[1]

You can create a reactive value data containing either the file or the text area content depending on the selected choice. This can be updated whenever the run button was clicked:

library(shiny)
library(readr)

ui <- fluidPage(tabPanel("Data",
  icon = icon("database"),
  tabsetPanel(
    type = "pills",
    tabPanel("Data Table",
      icon = icon("table"),
      sidebarLayout(
        sidebarPanel(
          selectInput("choose", "Choose file source", choices = c("file", "text"), selected = NULL),
          conditionalPanel(
            "input.choose=='file'",
            fileInput("data_file", "Upload coordinates in .bed/.csv format:", multiple = TRUE, accept = c(".bed", ".csv"))
          ),
          conditionalPanel(
            "input.choose=='text'",
            textAreaInput("data_paste", "Enter coordinates:", placeholder = "Paste like chr1 100 200 per line")
          ),
          actionButton("run", label = "Run overlap"),
          width = "3"
        ),
        mainPanel(textOutput("text"))
      )
    )
  )
))


server <- function(input, output, session) {
  data <- reactiveVal()

  observeEvent(
    eventExpr = input$run,
    handlerExpr = {
      switch(input$choose,
        file = read_file(input$data_file$datapath),
        text = input$data_paste
      ) %>% data()
    }
  )

  output$text <- renderText(data())
}

shinyApp(ui, server)

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1