2015-11-12 34 views
0

我創建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次,其中nlength(input$checkbox)

我試圖直接使用length(input$checkbox),試圖把該元素在numberInput()反應語句並返回它作爲列表,我想在接下來的方式使用reactiveValues()

v <- reactiveValues(n = length(input$checkbox)) 

    lapply(1:isolate(v$n), function(i) { 

然而,在所有這些實例Shiny抱怨缺乏活躍的被動背景。

那麼,我錯過了什麼?如何在反應環境之外使用樂器輸入的長度?

回答

1

我一般有使用this approach(只因爲它更容易讓我總結我的周圍頭)更多的運氣,但這個想法是使你的曲線到服務器上的用戶界面,然後呈現UI中ui.R

#server.R 
library(shiny) 
library(ggplot2) 

server <- shinyServer(function(input, output, session) { 
    output$checks <- renderText(input$checkbox) 

    output$plots <- renderUI({ 
    plot_output_list <- 
     lapply(input$checkbox, 
      function(i){ 
       plotOutput(paste0("plot", i)) 
      }) 
    do.call(tagList, plot_output_list) 
    }) 

    observe({ 
    for (i in input$checkbox) { 
     local({ 
     local_i <- i 
     output[[paste0("plot", local_i)]] <- 
      renderPlot({ 
      qplot(x = rnorm(100, mean = as.numeric(local_i))) + 
     ggtitle(paste("This plot was plotted with", local_i, "option")) 
      }) 
     }) 
    } 
    }) 



}) 

#ui.R 
library(shiny)  
ui <- shinyUI(fluidPage(
    title = 'lapply example', 

    sidebarLayout(
    sidebarPanel(
     checkboxGroupInput("checkbox", "Checkbox", 
         choices = sample(1:10, 5)) 
    ), 

    mainPanel(
     verbatimTextOutput("checks"), 
     uiOutput('plots') 
    ) 
) 
)) 

shinyApp(ui = ui, server = server) 
相關問題