我發現自己面臨一個問題:
我已經有了像這樣的閃亮應用程式(服務器部分):
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 等)的年數不同。 ……)。
因為我想動態確定圖形的數量。
如果您有任何線索,這將非常有用。
提前致謝。
uj5u.com熱心網友回復:
我們可以在資料框中創建所有圖,然后計算它們中有多少,以創建相應的輸出。
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/399159.html
標籤:for循环 闪亮的 闪亮的仪表板 闪亮的服务器 闪亮应用
