Reputation: 2186
I have generated a series of plots that I would like to loop through when generating a dynamic number of plots in a Shiny application. In the server function I have an observe function with the following structure:
server = function(input, output, session) {
<Lots of other code>
plotlist = generate_list_of_plots()
for(i in seq_len(length(plot list))) {
plotname = sprintf('ui_plot_%i', i)
output[[plotname]] = renderPlot(plotlist[[i]])
}
<Lots of other code>
}
Unfortunately, this does not function as I would like as the last plot in the list is repeated for each of the correlated plotOutput objects which were generated in a separate block of code. I believe this behavior is related to the fact that the renderPlot expressions are not called until the plots are made visible when the user clicks on a tab and the i
indexing variable has been advanced to its final position and is static each time the renderPlot function is executed, and therefore I get the same plot.
1: Is this the true cause of the issue? 2: If it is, what is the correct way to handle this type of situation?
Upvotes: 0
Views: 1061
Reputation: 2186
It seems as though I was able to locate a solution to the problem. I was correct in my assumption and the answer is the local
function. The solution was found in this post.
The corrected code would be the following:
server = function(input, output, session) {
<Lots of other code>
plotlist = generate_list_of_plots()
for(i in seq_len(length(plot list))) {
local({
my_i = i
plotname = sprintf('ui_plot_%i', my_i)
output[[plotname]] = renderPlot(plotlist[[my_i]])
})
}
<Lots of other code>
}
Upvotes: 1