我使用shinydashboard和gapminder的数据在Shiny中制作了一个简单的应用程序。基本版本正在运行,但我无法将其划分为模块。
应用程序正在根据用户选择绘制直方图:
-
列表中的大陆(数据中提供的所有大陆)
和
-
国家(根据所选大陆过滤国家)
代码和屏幕如下所示。
应用程序:
library(gapminder)
library(shiny)
library(shinydashboard)
library(dplyr)
ui <- dashboardPage(
skin = "yellow",
dashboardHeader(
title = "gapminder - data",
titleWidth = 300
),
dashboardSidebar(
width = 300,
sidebarMenu(
id="menu",
uiOutput("continent"),
uiOutput("country")
)
),
dashboardBody(
fluidRow(
plotOutput("plot")
))
)
server <- function(input, output, session) {
data <- reactive({
all_data <- filter(gapminder, country != "Kuwait")
all_data
})
output$continent <- renderUI({
data <- data()
selectInput("continent",
"CONTINENT:",
multiple = FALSE,
choices = sort(unique(data$continent)))
})
output$country <- renderUI({
data <- data()
ct <- input$continent
data %>%
filter(continent == ct) %>%
.$country %>%
unique() %>%
as.character() -> names
selectInput("country",
"COUNTRY:",
multiple = FALSE,
choices = names)
})
output$plot <- renderPlot({
data <- data()
ct <- input$continent
co <- input$country
data %>%
filter(continent == ct,
country == co) %>%
.$lifeExp ->selected_data
histogram <- hist(selected_data)
histogram
})
}
# Run the application
shinyApp(ui = ui, server = server)
我想用闪亮的模块重写它——将下拉字段放在单独的模块中。我收到了如下错误:
修改后的应用程序(带模块)的代码为:
library(gapminder)
library(shiny)
library(shinydashboard)
library(dplyr)
source("global.R")
ui <- dashboardPage(
skin = "yellow",
dashboardHeader(
title = "gapminder - data",
titleWidth = 300
),
dashboardSidebar(
width = 300,
sidebarMenu(
id="menu",
gapModuleUI("all")
) ),
dashboardBody(
fluidRow(
plotOutput("plot")
)
)
)
server <- function(input, output, session) {
callModule(gapModule, "all")
data <- reactive({
all_data <- filter(gapminder, country != "Kuwait")
all_data
})
output$plot <- renderPlot({
data <- data()
ct <- input$continent
co <- input$country
data %>%
filter(continent == ct,
country == co) %>%
.$lifeExp ->selected_data
histogram <- hist(selected_data)
histogram
})
}
# Run the application
shinyApp(ui = ui, server = server)
模块在全球范围内。R:
gapModuleUI <- function(id) {
ns <- NS(id)
tagList(
uiOutput(ns("continent")),
uiOutput(ns("country"))
)
}
gapModule <- function(input, output, session) {
ns <- session$ns
data <- reactive({
all_data <- filter(gapminder, country != "Kuwait")
all_data
})
output$continent <- renderUI({
data <- data()
selectInput(ns("continent"),
"CONTINENT:",
multiple = FALSE,
choices = sort(unique(data$continent)))
})
output$country <- renderUI({
data <- data()
ct <- reactive({input$continent})
data %>%
filter(continent == ct) %>%
.$country %>%
unique() %>%
as.character() -> names
selectInputns(ns("country"),
"COUNTRY:",
multiple = FALSE,
choices = names)
})
}
我应该在模块中更改什么?