我编写了一个小应用程序,您可以在其中看到一个单选按钮,您可以使用它在绘图图表和渲染表格之间切换。有用。之后我阅读了有关模块的 Shiny 文档并最终得到了这个应用程序:
我的应用程序R
library(shiny)
ui <- fluidPage(
fluidRow(
column(6,
chartTableSwitchUI("firstUniqueID")
)
)
)
server <- function(input, output) {
callModule(chartTableSwitch, "firstUniqueID")
}
shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)
我编写了一个 globar.R ,如下所示:
library(shiny)
library(plotly)
#define a simple dataframe for module example
X <- c("a", "b", "c")
Y <- c(1,2,3)
df <- data.frame(X,Y)
#UI function for first module
chartTableSwitchUI <- function(id){
ns <- NS(id)
tagList(
radioButtons("rb1", "View", choices = c(ns("Chart"), ns("Table")),
selected = "Chart", inline = TRUE),
conditionalPanel(
condition = "input.rb1 == 'Chart'", ns=ns,
plotlyOutput(ns("chart"))),
conditionalPanel(
condition = "input.rb1 == 'Table'", ns=ns,
tableOutput(ns("chartTable")))
)
}
#Server logic for first module
chartTableSwitch <- function(input, output, session){
output$chart <- renderPlotly(
plot_ly(df, x = ~X, y = ~Y)
)
output$chartTable <- renderTable(df)
}
Run Code Online (Sandbox Code Playgroud)
如果我运行该应用程序,单选按钮就会出现,但没有绘图或图表。只是单选按钮。
StackExchange 上的一些研究给了我提示,这可能是由于命名空间错误造成的,但我不知道问题到底是什么。
我的错误在哪里?
1)ns应该根据radioButtons名称(在您的情况下为“rb1”)调用函数,并且条件检查应该适应这一点。
2) 没有必要叫出ns你选择的名字。
将模块 UI 功能更改为:
#UI function for first module
chartTableSwitchUI <- function(id){
ns <- NS(id)
tagList(
radioButtons(ns("rb1"), "View", choices = c("Chart", "Table"),
selected = "Chart", inline = TRUE),
conditionalPanel(
condition = paste0('input[\'', ns('rb1'), "\'] == \'Chart\'"),
plotlyOutput(ns("chart"))),
conditionalPanel(
condition = paste0('input[\'', ns('rb1'), "\'] == \'Table\'"),
tableOutput(ns("chartTable")))
)
}
Run Code Online (Sandbox Code Playgroud)
另请参阅此问题以获取解释。