我目前正在按照{golem}
框架在不同的模块中对Shiny应用程序进行模块化。为了简单起见,假设我有3个主要的闪亮模块:
-
mod_faith_plot
:生成给定数据集的散点图(我将使用faitfhul)。 -
mod_points_select
:解耦下拉菜单以选择要绘制的点数。 UI输入具有此专用模块,因为我想将选择器放置在sidebarPanel
而不是mainPanel
中(在绘图旁)。 -
mod_data
:根据n_points
参数提供反应性数据框。
此模块在server
函数中相互交谈。
现在,当我在head(.,n_points())
中使用简单的mod_data
启动应用时,会收到以下警告:
Warning: Error in checkHT: invalid 'n' - must contain at least one non-missing element,got none.
在mod_points_select
参数被分配之前,NULL
中的输入显然是selected_points
,与我的 if相比,在启动时避免警告的方式更简洁,更优雅条件?
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,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,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,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)