在R闪亮中使用renderText()输出多行文本

Ale*_*lex 59 r shiny

我想使用一个renderText()命令输出多行文本.但是,这似乎不可能.例如,从闪亮的教程中我们截断了代码server.R:

shinyServer(
  function(input, output) {
    output$text1 <- renderText({paste("You have selected", input$var)
    output$text2 <- renderText({paste("You have chosen a range that goes from",
      input$range[1], "to", input$range[2])})
  }
)
Run Code Online (Sandbox Code Playgroud)

和代码ui.R:

shinyUI(pageWithSidebar(

  mainPanel(textOutput("text1"),
            textOutput("text2"))
))
Run Code Online (Sandbox Code Playgroud)

基本上打印两行:

You have selected example
You have chosen a range that goes from example range.
Run Code Online (Sandbox Code Playgroud)

是否有可能在两行合并output$text1,并output$text2成为一个代码块?到目前为止,我的努力都失败了,例如

output$text = renderText({paste("You have selected ", input$var, "\n", "You have chosen a range that goes from", input$range[1], "to", input$range[2])})
Run Code Online (Sandbox Code Playgroud)

有人有主意吗?

jdh*_*son 90

你可以使用renderUIhtmlOutput不是renderTexttextOutput.

require(shiny)
runApp(list(ui = pageWithSidebar(
  headerPanel("censusVis"),
  sidebarPanel(
    helpText("Create demographic maps with 
      information from the 2010 US Census."),
    selectInput("var", 
                label = "Choose a variable to display",
                choices = c("Percent White", "Percent Black",
                            "Percent Hispanic", "Percent Asian"),
                selected = "Percent White"),
    sliderInput("range", 
                label = "Range of interest:",
                min = 0, max = 100, value = c(0, 100))
  ),
  mainPanel(textOutput("text1"),
            textOutput("text2"),
            htmlOutput("text")
  )
),
server = function(input, output) {
  output$text1 <- renderText({paste("You have selected", input$var)})
  output$text2 <- renderText({paste("You have chosen a range that goes from",
                                    input$range[1], "to", input$range[2])})
  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/>'))

  })
}
)
)
Run Code Online (Sandbox Code Playgroud)

请注意,您需要使用<br/>换行符.您希望显示的文本也需要进行HTML转义,因此请使用该HTML功能.

  • 那个`HTML()`换行是离合器.乍一看,我担心这是一个黑客和唯一可用的选项...但实际上这个答案中的大多数代码来自问题的例子.切换到`renderUI({})`中的`HTML()`,然后在`ui.R`端切换到'htmlOutput()`非常简单.很好的答案! (3认同)
  • @Alex我想你也可以使用verbatimTextOutput()而不是textOutput(),但你可能不想要灰色阴影. (3认同)
  • 谢谢。我想没有html代码就没有办法做到这一点吗? (2认同)

the*_*ist 7

Joe Cheng说:

呃我不建议使用renderUIhtmlOutput[以其他答案中解释的方式].您正在处理基本上是文本的文本,并且在没有转义的情况下强制转换到HTML(意味着如果文本恰好包含包含特殊HTML字符的字符串,则可能会被错误地解析).

怎么样呢:

textOutput("foo"),
tags$style(type="text/css", "#foo {white-space: pre-wrap;}")
Run Code Online (Sandbox Code Playgroud)

(将#foo中的foo替换为textOutput的ID)