繁体   English   中英

在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

此代码的结果是:

这是您的州:阿拉巴马州这是您的州:阿拉斯加州这是 您的州:亚利桑那州这是您的州:阿肯色州

我想要的是:

这是您的州:阿拉巴马州阿拉斯加亚利桑那州阿肯色州

我已经提出了使用条件语句的解决方案,但是它很笨拙。 这是我在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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM