【发布时间】:2018-08-20 08:54:59
【问题描述】:
我在 Shiny 中使用 shinydashboard 和来自 gapminder 的数据制作了一个简单的应用程序。基本版本可以工作,但我不能把它分成模块。
该应用正在根据用户选择绘制直方图:
- 列表中的大陆(数据中可用的所有大陆) 和
- 国家/地区(根据所选大陆过滤国家/地区)
代码和屏幕如下。 应用:
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)
我想使用 Shiny Modules 重写它 - 将下拉字段放在单独的模块中。我收到了这样的错误:
修改后的应用程序(带模块)的代码是:
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)
并且模块在 global.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)
})
}
我应该对我的模块进行哪些更改?
【问题讨论】:
-
在
ui部分尝试使用ns <- NS(id)然后gapModuleUI(ns("all"))而不是gapModuleUI("all") -
@potockan,在
ui中,您的意思是ui <- dashboardPage(...?不幸的是,它不起作用。
标签: r module shiny shinydashboard