如何调用一次函数然后多次使用结果

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

我正在开发我的闪亮应用程序,我必须做的一件事是调用一个函数(returns 一个对象列表),然后在不同的多个调用中使用该函数的结果。不用说,我不想每次都需要引用列表中的对象之一时多次调用该函数。我将如何以最有效的方式实现这一目标?

例如,函数类似于 -

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)
}

现在,我想调用这个函数一次并将结果保存在一个变量中,这是我需要知道如何正确执行此操作的地方。

list_of_objects <- function_to_get_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

我希望我清楚我想用上面的例子实现什么,如果没有,请告诉我。

提前致谢!

AK

您可以使用 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]]
})

在修复了一些索引以引用列表元素后,我能够让它工作。

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)