html - 在Shiny中使用renderUI显示矢量

标签 html r vector shiny render

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

这里是一些示例代码:

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

关于html - 在Shiny中使用renderUI显示矢量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42119348/

相关文章:

r - 接下来 "specific"观察向后进位(NOCB)

r - 将 h2o 模型转换为非 h2o 模型

json - 写入/读取递归结构 S4 对象

c++ - std::vector 或 std::list 用于 std::unordered_map 存储桶?

html - 如何将 Google Earth KML 文件添加到 html iframe?

javascript - 防止 SVG 模式的拉伸(stretch)/preserveAspectRatio

html - 如何在列表框中放置滚动条?

html - 过渡中的图像未样式化以适合对象 : cover;

c++ - 我的范围循环出现逻辑错误

c++ - 将类对象放在 vector 中?