带条件面板的闪亮模块中的命名空间错误

时间:2018-09-18 08:00:55

标签: r module shiny

我编写了一个小应用程序,在其中您看到一个单选按钮,您可以使用该单选按钮在绘图图表和渲染表格之间切换。有用。之后,我阅读了有关模块的Shiny文档,并最终使用了此应用程序:

我的应用程序R

library(shiny)

ui <- fluidPage(  
  fluidRow(
    column(6,
           chartTableSwitchUI("firstUniqueID")
           )
    )
)

server <- function(input, output) {
  callModule(chartTableSwitch, "firstUniqueID")
}

shinyApp(ui = ui, server = server)

然后我编写了一个看起来像这样的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)
}

如果我运行该应用程序,则单选按钮在那里,但没有绘图或图表。只是单选按钮。

StackExchange上的一些研究提示我,这可能是由于命名间隔错误引起的,但我不知道到底是什么问题。

我的错误在哪里?

2 个答案:

答案 0 :(得分:0)

1)应该使用ns名称(在您的情况下为“ rb1”)调用radioButtons函数,并应对此进行条件检查。

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")))
  )
}

另请参见this question进行解释。

答案 1 :(得分:0)

您的解决方案是正确的,但需要进行一些小的更改。不要在radioButton的选择周围使用ns(),而应在radioButton的输入ID周围使用它,如下所示:

 radioButtons(ns("rb1"), "View", choices = c("Chart", "Table"), 
             selected = "Chart", inline = TRUE)

,它现在应该可以工作了。见下图

enter image description here