我希望能够在我的 Shiny 应用程序中将动态矢量显示为文本输出。我还想利用 HTML(粗体、字体颜色等),因此我使用 htmlOutput
和 renderUI
而不是 textOutput
和 renderText
每 this 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/