在 Shiny 中使用 renderUI 显示矢量图

Using renderUI in Shiny to display vectors

我希望能够在我的 Shiny 应用程序中将动态矢量显示为文本输出。我还想使用 HTML(粗体、字体颜色等),所以我使用 htmlOutputrenderUI 而不是 textOutputrenderText

下面是一些示例代码:

library(shiny)

shinyApp(

  ui <- htmlOutput("example"), 

  server <- function(input, output, session){

    # vector (in the real app, this is not a static vector--it will be updated with other inputs)
    states <- c("Alabama", "Alaska", "Arizona", "Arkansas")

    # text output
    output$example <- renderUI({

      x <- paste0("<strong>Here are your states</strong>: ", states)
      HTML(x)

    }) #END RENDERUI
  } #END SERVER
) #END SHINYAPP

这段代码的结果是:

Here are your states: Alabama Here are your states: Alaska Here are your states: Arizona Here are your states: Arkansas

我想要的是:

Here are your states: Alabama Alaska Arizona Arkansas

我想出了一个使用条件语句的解决方案,但它很笨拙。这是我为上述所需输出输入 renderUI 的内容:

x <- paste0("<strong>Here are your states: </strong>", 
            if(!is.na(states[1])){states[1]}, 
            if(!is.na(states[2])){states[2]},
            if(!is.na(states[3])){states[3]}, 
            if(!is.na(states[4])){states[4]})
HTML(x)

同样,上述解决方案有效,但它相当笨重,并且对于较大的向量(比方说,有 10 个以上的元素)来说效率非常低。有没有更简单的方法来显示这些向量,同时仍然能够利用 HTML?

您正在寻找 paste(..., collapse = " ").

library(shiny)

shinyApp(

  ui <- htmlOutput("example"), 

  server <- function(input, output, session){

    # vector (in the real app, this is not a static vector--it will be updated with other inputs)
    states <- c("Alabama", "Alaska", "Arizona", "Arkansas")

    # text output
    output$example <- renderUI({

      x <- paste0("<strong>Here are your states</strong>: ", paste(states, collapse = " "))
      HTML(x)

    }) #END RENDERUI
  } #END SERVER
) #END SHINYAPP