我正在尝试将仪表板的一些代码分解为模块。我在处理这段rCharts
代码时遇到了问题。我可以将它作为一个应用程序运行,但理想情况下我想将它拆分为UI
和server
函数,以便我可以将它们保存在一个包中。
下面的代码显示了应用程序中的工作代码和作为模块的损坏代码。谁能指出我做错了什么?
谢谢
---
title: "Example"
output:
flexdashboard::flex_dashboard:
runtime: shiny
---
```{r setup, include=FALSE}
library(flexdashboard)
library(shiny)
library(rCharts)
X <- data.frame(Var1 = rep(1:10, 3),
Var2 = rep(c("control", "treatment1", "treatment2"), each = 10),
Freq = abs(rnorm(30, 0, 1))
)
```
Column {data-width=650}
-----------------------------------------------------------------------
### Broken Code as Module
```{r}
ui2 = function(id) {
ns = NS(id)
mainPanel(plotOutput("plot1", height = "100%"),
showOutput(ns("histogram"), "nvd3"))
}
server2 = function(input, output, session) {
output$histogram <- renderChart2({
n2 <- nPlot(Freq ~ Var1, group = 'Var2', data = X, type = 'multiBarChart')
n2$set(width = session$clientData$output_plot1_width)
n2
})
}
ui2("example")
callModule(server2, "example")
```
Column {data-width=350}
-----------------------------------------------------------------------
### Working Code as App
```{r}
shinyApp(
ui = mainPanel(
plotOutput("plot2", height = "100%"),
showOutput("histogram", "nvd3")
),
server = function(input, output, session) {
output$histogram <- renderChart2({
n2 <- nPlot(Freq ~ Var1, group = 'Var2', data = X, type = 'multiBarChart')
n2$set(width = session$clientData$output_plot2_width)
n2
})
}
)
```
### Template
```{r}
```
更新以响应@HubertL 的回复
下面的代码,当附加到上面的主体时,说明了flexdashboard
可以将shiny
应用程序作为独立函数运行的方式(注意runtime: shiny
标题中的)。
这里的独立函数可以存放在库中随意调用,不需要用shinyApp
.
澄清一下,我要问的问题是我如何才能完成将rCharts
情节调用为一系列独立的 UI 和服务器功能,就像我可以用 normal 做的那样plots
,或者如果这不可能,为什么不呢?
Stand Alone Example
======================================================================
Inputs{.sidebar}
-----------------------------------------------------------------------
```{r}
## UI for choosing species
iris_plotUI = function(id) {
ns = NS(id)
# User choices for line
list_species = list(
"Setosa" = "setosa",
"Versicolor" = "versicolor",
"Virginica" = "virginica"
)
flowLayout(
# input: Tube line selection
selectInput(
ns("type"),
label = h3("Select Species:"),
choices = list_species,
selected = "setosa"
)
)
}
# server module
iris_plot = function(input, output, session) {
library(MASS)
library(data.table)
dt = data.table::copy(iris)
data.table::setDT(dt)
iris_filtered = reactive({
dt[Species == input$type]
})
output$scatter = renderPlot({
plot(iris_filtered()$Petal.Width,
iris_filtered()$Petal.Length)
})
}
# plotting module
iris_plotOutput = function(id) {
ns = NS(id)
plotOutput(ns("scatter"))
}
## call inputs in the sidebar
iris_plotUI("ns_iris")
```
Column
-----------------------------------------------------------------------
```{r}
## all server module and plot (plot in main panel)
callModule(iris_plot, "ns_iris")
iris_plotOutput("ns_iris")
```
WRT 命名约定,这已在博客文章的评论中得到澄清。消息:
我有点不清楚,后缀 UI、输入、输出会影响行为还是建议的命名约定?
其中一位作者已回答:
只是一个建议的命名约定,它们不会影响任何东西。