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

时间:2014-04-23 01:58:43

标签: r shiny

我想使用一个renderText()命令输出多行文本。但是,这似乎不可能。例如,shiny tutorial我们在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])})
  }
)

ui.R中的代码:

shinyUI(pageWithSidebar(

  mainPanel(textOutput("text1"),
            textOutput("text2"))
))

基本上打印两行:

You have selected example
You have chosen a range that goes from example range.

是否可以将两行output$text1output$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])})

有人有什么想法吗?

3 个答案:

答案 0 :(得分:85)

您可以使用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/>'))

  })
}
)
)

请注意,您需要使用<br/>作为换行符。您希望显示的文本也需要进行HTML转义,因此请使用HTML函数。

答案 1 :(得分:7)

根据Joe Cheng

  

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

     

相反如何:

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

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

答案 2 :(得分:-1)

如果你的意思是你不关心换行符:

output$text = renderText({
  paste("You have selected ", input$var, ". You have chosen a range that goes 
  from", input$range[1], "to", input$range[2], ".")
})