【问题标题】:Shiny apps - embedding reactive expression in if-then statement闪亮的应用程序 - 在 if-then 语句中嵌入反应式表达式
【发布时间】:2015-09-22 15:00:20
【问题描述】:

我很难在 Shiny Apps 中使用反应式表达。我正在从滑块输入创建一个饼图。这一切都很好,但是,标签重叠。为了避免这种情况,当输入为零时,我想要标签“”。困难在于我无法在 if-then 语句中嵌入反应式表达式。

这是一个 MWE...

文件“ui.R”...

library(shiny)

shinyUI(fluidPage(

  titlePanel("Exposure to English calculator"),

  sidebarLayout(
    sidebarPanel(

      h3("Sleeping"),

      sliderInput("sleep", "How long does your child sleep every day?",
                               min=0, max=15, value=0, step = 0.5),

    h3("School"),
    sliderInput("school", "How long does your child spend in school?",
                min = 0, max = 50, value=0, step = 0.5)
    ),

    mainPanel(
      plotOutput("plot")
    )



  )
))

文件服务器.R...

library(shiny)

values <- c(1,2)

# Define server logic for slider examples
shinyServer(function(input, output) {


  total_sleep <- reactive({7*input$sleep})

  pieLabels<-c("sleep", "school", "other")

  if(total_sleep() == 0) {
    pieLabels[1] <- ""
  }

  output$plot <- renderPlot({ 

    pie(c(total_sleep(), input$school, 50),
        labels = pieLabels,
        col = c("deepskyblue", "orange"),
        height = 1500
    )

  })


})

编译由于“if”表达式而崩溃,即使我在它后面加上了括号,以表明它是从反应式表达式派生的。

提前致谢。

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    您可以将所有total_sleep 代码和条件语句放在renderPlot 函数中:

    library(shiny)
    
    app <- shinyApp(
      ui = shinyUI(fluidPage(
        titlePanel("Exposure to English calculator"),
        sidebarLayout(
          sidebarPanel(
            h3("Sleeping"),
            sliderInput("sleep", "How long does your child sleep every day?",
                        min=0, max=15, value=0, step = 0.5),
            h3("School"),
            sliderInput("school", "How long does your child spend in school?",
                        min = 0, max = 50, value=0, step = 0.5)
          ),
          mainPanel(
            plotOutput("plot")
          )
        )
      )),
      server = shinyServer(function(input, output) {
        output$plot <- renderPlot({ 
          total_sleep <- 7*input$sleep
          pieLabels<-c("sleep", "school", "other")
          if(total_sleep == 0) {
            pieLabels[1] <- ""
          }
          pie(c(total_sleep, input$school, 50),
              labels = pieLabels,
              col = c("deepskyblue", "orange")
          )
        })
      }))
    
    runApp(app)
    

    请注意,我从 pie 中删除了 height,因为该参数不存在并且会发出警告。

    【讨论】:

    • 谢谢。美丽的!我知道这会很简单,但我摆弄了几个小时......
    猜你喜欢
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    • 2022-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    相关资源
    最近更新 更多