使用 sprintf() 进行简洁

Using sprintf() for concision

我正在尝试缩短我的这部分代码——具体来说,if、else if 语句通过使用 sprintf() 并仅更改侧边栏面板的颜色。我该怎么做?


output$calculation<-renderUI({
          req(input$popDensity)
          populationDensity <- input$popDensity;
          likelihood <- populationDensity/500

        if (likelihood()>1) {
          sidebarPanel(style="background-color: red; width: 300px; height: 300px;", h3("Extreme risk!"))

        } else if (likelihood()>.65){
          sidebarPanel(style="background-color: orange; width: 300px; height: 300px;",
                       h3("Very high risk!"))
        }
        else if (likelihood()>.35){
          sidebarPanel(style="background-color: yellow; width: 300px; height: 300px;",
                       h3("High risk!"))
        }
        else if (likelihood()>.10){
          sidebarPanel(style="background-color: blue; width: 300px; height: 300px;",
                       h3("Moderate risk!"))

        } else {
          sidebarPanel(style="background-color: #39ac39; width: 300px; height: 300px;",
                       h3("Low risk!"))

        }

      })

不确定如何将 sprintf() 包含在其中。我通过使用 shinyjs 更改 sidebarPanel class 使其相当简洁。这是 app.R:

library(shiny)
library(shinyjs)
library(dplyr)

# Define UI for application that draws a histogram
ui <- fluidPage(
    
    useShinyjs(),
    
    # Application title
    titlePanel("Colour slider"),
    
    tags$head(
        tags$style(HTML("
        
      .sidebar {
        width: 300px;
        height: 300px;
      }
        
      .red { background-color: red; }
      .orange { background-color: orange; }
      .yellow { background-color: yellow; }
      .blue { background-color: blue; }
      .green { background-color: #39ac39; }

    "))
    ),
    
    sidebarLayout(
        sidebarPanel(
            id = "sidebar",
            class = "sidebar",
            textOutput("header") %>% 
                tagAppendAttributes(class = "h3")
        ),
        
        mainPanel(
            sliderInput("popDensity",
                        "Population Density",
                        min = 1,
                        max = 600,
                        value = 10)
        )
    )
)

fun <- function(x, y) {
    
    removeClass("sidebar", c("red", "orange", "yellow", "blue", "green"))
    addClass("sidebar", y)
    
    x
}

# Define server logic required to draw a histogram
server <- function(input, output) {
    
    output$header <- renderText({
        
        req(input$popDensity)
        
        likelihood <- input$popDensity / 500
        
        if (likelihood > 1)
            fun("Extreme risk!", "red")
        else if (likelihood > 0.65) 
            fun("Very high risk!", "orange")
        else if (likelihood > 0.35) 
            fun("High risk!", "yellow")
        else if (likelihood > 0.10) 
            fun("Moderate risk!", "blue")
        else 
            fun("Low risk!", "green")
        
    })
}

# Run the application 
shinyApp(ui = ui, server = server)