gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:25:31 25 4
gpt4 key购买 nike

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

例如,函数类似于 -

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

关于shiny - 如何调用一次函数然后多次使用结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37634614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com