R语言 使用htmlOutput将矢量渲染为闪亮应用程序中的逗号分隔文本

vxf3dgd4  于 2022-12-25  发布在  其他
关注(0)|答案(3)|浏览(142)

我想使用htmlOutput在shiny应用程序中渲染文本。如果我在选择输入中只选择了一个对象,应用程序就可以工作!一旦input$var有多个对象,结果就不是我预期的那样

require(shiny)
runApp(list(ui = pageWithSidebar(
  headerPanel("Test"),
  sidebarPanel(
    selectInput("var", 
                label = "Choose a variable to display",
                choices = c("Text01", "Text02",
                            "Text03", "Text04"),multiple = TRUE,
                selected = "Text01"),
    sliderInput("range", 
                label = "Range of interest:",
                min = 0, max = 100, value = c(0, 100))
  ),
  mainPanel(htmlOutput("text"))
),
server = function(input, output) {
  
  output$text <- renderUI({
    str1 <- paste("You have selected", input$var)
    str2 <- paste("You have chosen a range that goes from",
                  input$range[1], "to", input$range[2])
    HTML(paste(str1, str2, sep = '<br/>'))
    
  })
}
)
)

我如何修改代码以获得如下输出:

You have selected Text01,Text02
You have chosen a range that goes from 0 to 100.
hfyxw5xn

hfyxw5xn1#

换条线就行了

str1 <- paste("You have selected", input$var)

str1 <- paste("You have selected", paste(input$var, collapse = ", "))

问题是当input$var有一个以上的元素时,paste()返回一个字符串向量,而使用collapse可以将字符串向量input$var减少为一个值。

col17t5w

col17t5w2#

library(shiny)

runApp(list(ui = pageWithSidebar(
  headerPanel("Test"),
  sidebarPanel(
    
    selectInput("var", 
                label = "Choose a variable to display",
                choices = c("Text01", "Text02",
                            "Text03", "Text04"), multiple = TRUE,
                selected = "Text01"),
    
    sliderInput("range", 
                label = "Range of interest:",
                min = 0, max = 100, value = c(0, 100))
  ),
  mainPanel(htmlOutput("text"))
),
server = function(input, output) {
  
  output$text <- renderUI({
    
    
    str1 <- paste(input$var, collapse = " ")
    str2 <- paste("You have chosen a range that goes from",
                  input$range[1], "to", input$range[2])
    
    
    tagList(
      div("You have selected", str1),
      div(str2))
  })
}
)
)
zlhcx6iw

zlhcx6iw3#

我建议使用基R函数toString(),而不是第二个paste

library(shiny)

runApp(list(
  ui = pageWithSidebar(
    headerPanel("Test"),
    sidebarPanel(
      selectInput(
        "var",
        label = "Choose a variable to display",
        choices = c("Text01", "Text02",
                    "Text03", "Text04"),
        multiple = TRUE,
        selected = "Text01"
      ),
      sliderInput(
        "range",
        label = "Range of interest:",
        min = 0,
        max = 100,
        value = c(0, 100)
      )
    ),
    mainPanel(htmlOutput("text"))
  ),
  server = function(input, output) {
    output$text <- renderUI({
      str1 <- paste("You have selected", toString(input$var))
      str2 <- sprintf("You have chosen a range that goes from %s to %s", input$range[1], input$range[2])
      HTML(paste(str1, str2, sep = '<br/>'))
    })
  }
))

相关问题