1

I'm trying to learn how to use shiny modules to simplify a messy shiny app I have. The app currently reads in several data sets using a list of names like this:

dataSetsToLoad <- c("set1name", "set2name", "etc")
for (i in 1:length(dataSetsToLoad) {
dt <- readRDS(paste0(dataSetsToLoad[i], ".RDS")
assign(dataSetsToLoad[i], dt)
}

These end up in the global environment and are accessible to all my non-modularized code.

Following a code pattern from here, I'd like to modify the above to something like the following

stash = reactiveValues()
 for (i in 1:length(dataSetsToLoad) {
      stashVar <- paste0("stash$", dataSetsToLoad[i])
      dt <- readRDS(paste0(dataSetsToLoad[i], ".RDS")
      assign(stashVar, dt)
}

The summary question is how do I put the dt into the stash reactive with the dynamically created name in stashVar. A second question is whether there is any way to test this without actually running it in a shiny app.

2
  • 1
    save(df2, df1, file = "data.RData"). Did you know you can do something like this? You can easily save and load multiple data.frames in one RData File. Commented Jun 2, 2019 at 17:45
  • This is very useful! Thanks! But I don't see how it solves my problem of getting the data into stash. Commented Jun 2, 2019 at 18:49

1 Answer 1

2

You can do something like this. Store the dataframes in a list and then assign them in a loop to the reactiveValues().

dflist <- list(mtcars, airquality, mtcars)

library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

    # Application title
    titlePanel("Old Faithful Geyser Data"),

    # Sidebar with a slider input for number of bins 
    sidebarLayout(
        sidebarPanel(
            sliderInput("bins",
                        "Number of bins:",
                        min = 1,
                        max = 3,
                        value = 3)
        ),

        # Show a plot of the generated distribution
        mainPanel(
           plotOutput("distPlot")
        )
    )
)

# Define server logic required to draw a histogram
server <- function(input, output) {

    values <- reactiveValues()

    for(i in 1:length(dflist)) {
        values[[paste0("df_", i)]] <- dflist[[i]]
    }

    observeEvent(input$bins, {
        print(values$df_1)
        print(values$df_2)
        print(values$df_3)
    })


}

# Run the application 
shinyApp(ui = ui, server = server)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.