2

我目前正在按照{golem}框架在不同的模块中模块化一个闪亮的应用程序。为简单起见,假设我有 3 个主要的闪亮模块:

  • mod_faith_plot:生成给定数据集的散点图(我将使用 faitfhul)。
  • mod_points_select:解耦下拉菜单以选择要绘制的点数。UI 输入有这个专用模块,因为我想将选择器放在sidebarPanel而不是mainPanel(在绘图旁边)。
  • mod_data:根据n_points参数提供反应式数据框。

这些模块在server函数中相互通信。现在,当我用一个简单head(., n_points())的 in启动我的应用程序时,mod_data我收到以下警告:

Warning: Error in checkHT: invalid 'n' -  must contain at least one non-missing element, got none.

输入mod_points_select显然是在分配参数NULL之前,有没有比我的ifselected_points条件更简洁和更优雅的方法来避免启动时的警告?

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

# [Module] Plot faithful data -------------------------------------------------------

mod_faith_plot_ui <- function(id){
  ns <- NS(id)
  tagList(
    plotOutput(ns("faith_plot"))
  )
}

mod_faith_plot_server <- function(input, output, session, data){
  ns <- session$ns

  output$faith_plot <- renderPlot({
    data() %>% 
      ggplot(aes(eruptions, waiting)) +
      geom_point()
  })

}


# [Module] Module for n_points dropdown ---------------------------------------------

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

  uiOutput(ns("select_points"))

}

mod_points_select_server <- function(input, output, session){
  ns <- session$ns

  output$select_points <- renderUI({
    selectInput(
      ns("n_points"),
      label = "Select how many points",
      choices = seq(0, 200, by = 10),
      selected = 50
    )
  })
  reactive({input$n_points})
}


# [Module] Get filtered data -----------------------------------------------------------------

mod_data_server <- function(input, output, session, n_points){
  ns <- session$ns

  data <- reactive({
    faithful %>%
      # If condition used to avoid warnings at startup - switch lines to get warning
      # head(., n_points())
      head(., if(is.null(n_points())) { TRUE } else {n_points()})
  })

}


ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      mod_points_select_ui(id = "selected_points")
    ),
    mainPanel(
      tabsetPanel(type = "tabs",
                  tabPanel("plot", mod_faith_plot_ui(id = "faith_plot"))
      )
    )
  )
)

server <- function(input, output, session) {

  data <- callModule(mod_data_server, id = "data", n_points = selected_points)
  selected_points <- callModule(mod_points_select_server, id = "selected_points")

  callModule(mod_faith_plot_server, id = "faith_plot", data = data)
}

shinyApp(ui, server)

4

1 回答 1

2

您可以使用req()来确保值可用:

data <- reactive({
    req(n_points())
    faithful %>%
        head(., n_points())
})

当值不可用时,呼叫被静默取消

于 2020-06-19T17:18:19.877 回答