闪亮:在模块或嵌套模块中使用uiOutput?

时间:2016-07-21 20:35:21

标签: r shiny

在我的应用程序中,我有一个模块嵌套在另一个模块中。父模块和子模块都使用renderUI(滑块)创建UI输出,并根据此滑块的值过滤ggplot上显示的数据。我在常规的ui /服务器情况下熟悉这种模式 - 但是,我不确定如何在模块中访问滑块的值。

下面的代码显示我的尝试为UI调用的模块和嵌套模块执行此操作。

library(shiny)
library(dplyr)
library(ggplot2)


ui <- fluidPage(
  fluidRow(
    outerModUI("outer")
  )
)

outerModUI <- function(id) {
  ns <- NS(id)
  fluidPage(fluidRow(
    uiOutput(ns("outer_slider")),
    plotOutput(ns("outer_plot")),
    innerModUI(ns("inner"))
  ))
}

innerModUI <- function(id) {
  ns <- NS(id)

  fluidPage(fluidRow(
    uiOutput(ns("inner_slider")),
    plotOutput(ns("inner_plot"))
  ))
}


server <- function(input, output, session) {
  callModule(outerMod, "outer")

  output$outer_slider <- renderUI({
    sliderInput("slider1", label = "outer slider", min = round(min(mtcars$mpg)), 
      max = round(max(mtcars$mpg)), value = c(min(mtcars$mpg), max(mtcars$mpg), step = 1))
  })

  output$outer_plot <- renderPlot({
    data <- filter(mtcars, between(mpg, input$slider1[1], input$slider1[2]))
    ggplot(data, aes(mpg, wt)) + geom_point()
  })
}

outerMod <- function(input, output, session) {
  callModule(innerMod, "inner")
}

innerMod <- function(input, output, session) {
  output$inner_slider <- renderUI({
    sliderInput("slider2", label = "inner slider", min = round(min(mtcars$mpg)), 
      max = round(max(mtcars$mpg)), value = c(min(mtcars$mpg), max(mtcars$mpg), step = 1))
  })

  output$inner_plot <- renderPlot({
    data <- filter(mtcars, between(mpg, input$slider2[1], input$slider2[2]))
    ggplot(data, aes(mpg, wt)) + geom_point()
  })
}


shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:3)

Joe Cheng在光鲜的讨论邮件列表上提供了答案。

  

1)在输出$ inner_slider的renderUI中,将sliderInput(“slider2”,...)更改为sliderInput(session $ ns(“slider2”),...)。这就是你如何获得当前模块实例(innerMod)的命名空间。

     

2)我还将它添加到输出$ inner_plot的第一行:   REQ(输入$ slider2)

     

这表示该绘图的渲染不应该继续,除非输入$ slider2的值存在(它不会在应用启动时出现)。

这里有一个工作要点,其中renderUI在父模块和子模块中都能正常工作。 https://gist.github.com/tbadams45/38f1f56e0f2d7ced3507ef11b0a2fdce

相关问题