Shiny: change data source

Hi there, I really need some help. I am trying to make a shiny app where, based on the choice made with Radio Buttons, I use different data source. I actually managed to do that by using reactive({switch(....))} but the problem is that I end up working with render objects when I actually need a matrix.
Is there any way to end up getting my data into a matrix?

I hope my doubt is clear,
Thanks.

Hi,

Welcome to the RStudio community!

OPTION 1 - Read data from disk when needed
Here is an example on how to read different datasets when needed

library(shiny)

#Generate test datasets (only needed once)
write.csv(data.frame(x = 1:10, y = runif(10)), "seta.csv", row.names = F)
write.csv(data.frame(a = LETTERS[1:15], b = sample(1:15), c = T), "datasetb.csv", row.names = F)

#UI
ui <- fluidPage(

  radioButtons("dataChoice", "Data Set", choices = c("Set A" = "seta.csv", "Set B" = "datasetb.csv")),
  tableOutput("myTable")

)

#SERVER
server <- function(input, output, session) {
  
  myData = reactive({
    read.csv(input$dataChoice)
  })
  
  output$myTable = renderTable({
    myData()
  })
  
}

shinyApp(ui, server)

Note that the first part, to generate the datasets can be removed after is has been run once. It's just there to make the dummy app work, as it needs data sets to load.

OPTION 2 - All data in memory, switch when needed
Another way of doing this in case you like to keep all datasets in memory and not load it every time, is by evaluating a string (choice) as a variable like this:

library(shiny)

#Generate test datasets (only needed once)
write.csv(data.frame(x = 1:10, y = runif(10)), "seta.csv", row.names = F)
write.csv(data.frame(a = LETTERS[1:15], b = sample(1:15), c = T), "datasetb.csv", row.names = F)

#UI
ui <- fluidPage(

  radioButtons("dataChoice", "Data Set", choices = c("Set A" = "setA", "Set B" = "setB")),
  tableOutput("myTable")

)

#SERVER
setA = read.csv("seta.csv")
setB = read.csv("datasetb.csv")

server <- function(input, output, session) {
  
  output$myTable = renderTable({
    eval(parse(text = input$dataChoice))
  })
  
}
shinyApp(ui, server)

The eval(parse(text = input$dataChoice)) part will interpret a string as a variable and thus switch the set that's displayed (though both are loaded in memory)

Hope this helps,
PJ

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.