ashishkul
ashishkul

Reputation: 405

How to call a function once and then use the results multiple times

I am working on my shiny application and one of the thing I have to do is to call one function (which returns a list of objects) and then use the result of that in different multiple calls. Needless to say, I don't want to call the function multiple times, every time I need reference to one of the object from the list. How would I achieve this in the most efficient way?

Example, function is something like -

function_to_get_list <- function(){
  # first, input data is read at some point then this function is called
  if(!is.null(input_data)){
    ... some processing and calls to create the list of objects
    return(list_of_object)
  }
  else 
    return(NULL)
}

Now, I want to call this function once and save the results in a variable, this is where I need to know how to do this correctly.

list_of_objects <- function_to_get_list()

and then just use that variable to reference elements of that list.

output$text1 <- renderText({
  list_of_objects[[1]]
})

output$text2 <- renderText({
  list_of_objects[[2]]
})

# use of renderText is just to illustrate the calls to use the list

I hope I am clear on what I want to achieve using the above example, if not, please let me know.

Thanks in advance!

AK

Upvotes: 4

Views: 2683

Answers (2)

ashishkul
ashishkul

Reputation: 405

I was able to get it work after fixing some indexing to reference the list elements.

library(shiny)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      actionButton("action", "RUN")
    ),
    mainPanel(
      textOutput("text1"),
      textOutput("text2")
    )
  )
)

server <- function(input, output) {

  values <- reactiveValues()

  function_to_get_list <- function(){
    return(list(c(1:5)))
  }

  values[['1']] <- function_to_get_list()

  output$text1 <- renderText({
    if(input$action > 0)
      paste("1st element of list ", values[['1']][[1]][[1]])
  })

  output$text2 <- renderText({
    if(input$action > 0)
      paste("2nd element of list ", values[['1']][[1]][[2]])
  })

}

shinyApp(ui = ui, server = server)

Upvotes: 1

Mikael Jumppanen
Mikael Jumppanen

Reputation: 2486

You can do that by using reactiveValues(). Reference

values <- reactiveValues()

function_to_get_list <- function(){
  # first, input data is read at some point then this function is called
  if(!is.null(input_data)){
    ... some processing and calls to create the list of objects
    values[[1]] <- list_of_objects
  }
  else 
    return(NULL)
}

output$text1 <- renderText({
  values[[1]][[1]]
})

output$text2 <- renderText({
  values[[1]][[2]]
})

Upvotes: 4

Related Questions