我創建Shiny應用程序,我想使用checkboxGroupInput爲了打印出多個圖。但是,我想僅打印出checkboxGroupInput中檢查過的元素的圖。在Shiny圖庫中有一個類似的example用於在使用lapply的循環中創建UI元素。下面是一個例子的簡化版本,以顯示我想要做的:使用checkboxGroupInput的長度作爲循環的輸入來創建多個元素
#server.R
library(shiny)
library(ggplot2)
shinyServer(function(input, output, session) {
numberInput <- reactive({
input$checkbox
})
lapply(1:10, function(i) {
output[[paste0('b', i)]] <- renderPlot({
qplot(x = rnorm(100, mean = as.numeric(numberInput()[i]))) +
ggtitle(paste("This plot was plotted with", numberInput()[i], "option"))
})
})
})
#ui.R
library(shiny)
shinyUI(fluidPage(
title = 'lapply example',
sidebarLayout(
sidebarPanel(
checkboxGroupInput("checkbox", "Checkbox",
choices = sample(1:10, 5))
),
mainPanel(
lapply(1:10, function(i) {
plotOutput(paste0('b', i))
})
)
)
))
這工作,但很明顯,當閃亮的嘗試提取numberInput()[i]
其中i
比當前選中的元素的數量大,沒有什麼可提取而不是一個情節有一個錯誤。因此,我需要以某種方式告訴lapply
只重複n
次,其中n
是length(input$checkbox)
。
我試圖直接使用length(input$checkbox)
,試圖把該元素在numberInput()
反應語句並返回它作爲列表,我想在接下來的方式使用reactiveValues()
:
v <- reactiveValues(n = length(input$checkbox))
lapply(1:isolate(v$n), function(i) {
然而,在所有這些實例Shiny抱怨缺乏活躍的被動背景。
那麼,我錯過了什麼?如何在反應環境之外使用樂器輸入的長度?