【问题标题】:Multiple Condition in Shiny Dashboard闪亮仪表板中的多个条件
【发布时间】:2019-07-26 14:44:35
【问题描述】:

下面是一个例子,但在目前的情况下,我有很多条件要通过,我不想使用 if 语句。如果我能完成工作,有没有其他不使用的方法。

代码


library(shiny)

ui = fluidPage(
  selectInput('p_id','ID:', c(111,222,333)),
  uiOutput('uiID')
)

server = function(input, output, session) {

  maxdays <- reactive({
    if(input$p_id %in% c(111)){
      x = 1
    }else{
      if(input$p_id %in% c(222)){
        x = 2
      }else
        x = 3 
    }
    return(x)
  })


  output$uiID <- renderUI({
    selectInput('days','Days:', choices=seq(1,maxdays()))
  })


}

runApp(shinyApp(ui = ui, server = server))

【问题讨论】:

  • v &lt;- c(111,222,333); which(v==111); which(v==222)
  • 您的示例确实有效。这不是编写 if else 语句的最佳方式,但仍然如此。为什么不想使用 if 语句?
  • @Wilmar van Ommeren。我现在的情况是,如果我使用 if 条件,那么我必须写大约 700 个 if 条件,那么只有我才能得到准确的输出。我不想这样做,因为我觉得这不是正确的方法。如果您有任何建议,请告诉我。

标签: r shiny


【解决方案1】:

假设maxdays 基本上返回您的selectInput 选择的位置,您可以执行以下操作:

library(shiny)

my_choices <- c(111, 222, 333)

ui <- fluidPage(
  selectInput('p_id', 'ID:', my_choices),
  uiOutput('uiID')
)

server <- function(input, output, session) {
  maxdays <- reactive(which(my_choices %in% input$p_id))

  output$uiID <- renderUI({
    selectInput('days', 'Days:', choices = seq(1,maxdays()))
  })
}

shinyApp(ui, server)

【讨论】:

    【解决方案2】:

    最好不要一直使用renderUI 重新创建对象,而是我们可以简单地更新小部件:

    library(shiny)
    
    data <- c(111,222,333)
    ui <- fluidPage(
      selectInput('p_id','ID:', data),
      selectInput('days','Days:', choices = NULL)
    )
    
    server = function(input, output, session) {
    
      observeEvent(input$p_id,{
        mseq <- seq(1,which(data %in% input$p_id))
        updateSelectInput(session,"days","Days:",choices = mseq)
      })
    
    }
    runApp(shinyApp(ui = ui, server = server))
    

    【讨论】:

      猜你喜欢
      • 2018-04-28
      • 2015-04-22
      • 1970-01-01
      • 2020-06-10
      • 1970-01-01
      • 1970-01-01
      • 2019-02-12
      • 2016-01-11
      • 2018-05-30
      相关资源
      最近更新 更多