双循环以检查闪亮应用程序中的动态图数

Double for loop to check dynamic number of plots in shiny app

我发现自己遇到了一个问题:

我已经有了像这样的闪亮应用程序(服务器部分):

observe({
      data <- my_function() %>%
       filter(col1 == "X1")

h <- sort(unique(data$year))

nb <- length(h)
lst <- as.list(h)

output$plot_name <- renderUI({
  plot_output <- lapply(1:nb,
                                 function(n1) {
                                   plotname <- paste0("plots", n1)
                                   plotOutput(plotname)
                                 })
  do.call(tagList, plot_output)
})

my_data <- list()

i <- 0
for (i in 1:length(lst)) {
  
  local({
    my_i <- i
    plotname <- paste0("plots", my_i)
    my_data[[my_i]] <- data %>% 
      filter(year == lst[[my_i]])
    
    output[[plotname]] <- renderPlot({
      
      g <- ggplot(..........)
      
      print(g)
      
    })
    
  })
}

})

这允许我每年输出给定 X 的图表。

但是我想删除过滤器并为每个 X 的每一年制作一个图表,因为我知道所有 X 的年数都不相同(X1:2000,X2:2000 和 2001,X3 : 2001 等......).

因为我想动态确定图表的数量。

如果你有任何线索,那将非常有用。

提前致谢。

我们可以在一个数据框中创建所有的图,然后计算它们的数量以创建相应的输出。

library(tidyverse)
library(shiny)


df <-
  read_table("col1 col2 year pts
X1 1 2000 24 
X1 2 2001 36 
X2 1 2000 48
X1 0 2000 24
X3 1 2000 72
X2 1 2000 24
X2 2 2002 48
X3 2 2001 24")



ui <- fluidPage(
  uiOutput("plot_name")
)

server <- function(input, output, session) {
  my_function <- reactive({
    df
  })
  
  observeEvent(my_function, {
    data <- my_function() 
    

# Create the plots --------------------------------------------------------

    
    plots_df <- 
      data %>% 
      group_by(col1, year) %>%
      summarise(plot = list(
        ggplot(cur_data_all() ,aes(x = pts, y = col2)) +
          geom_point() +
          ggtitle(paste('col:', col1 ,'year:', year))
      ))
    

# plots UI ----------------------------------------------------------------

    
    nb <- length(plots_df$plot)
    plotname <- paste0("plots", 1:nb) # save the names for renderPlot functions

    output$plot_name <- renderUI({
      plot_output <- lapply(
        plotname,
        function(n1) {
          plotOutput(n1)
        }
      )
      do.call(tagList, plot_output)
    })


# renderPlot funcitons ----------------------------------------------------


    walk2(plotname, plots_df$plot, ~ {
      output[[.x]] <<- renderPlot({
        .y
      })
    })
   })
}

shinyApp(ui, server)