Outputting multiple lines of text with renderText() in R shiny
I want to output multiple lines of text using one renderText()
command. However, this does not seem possible. For example, from the shiny tutorial we have truncated code in 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])})
}
)
and code in ui.R
:
shinyUI(pageWithSidebar(
mainPanel(textOutput("text1"),
textOutput("text2"))
))
which essentially prints two lines:
You have selected example
You have chosen a range that goes from example range.
Is it possible to combine the two lines output$text1
and output$text2
into one block of code? My efforts so far have failed, e.g.
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])})
Anyone have any ideas?
Solution 1:
You can use renderUI
and htmlOutput
instead of renderText
and textOutput
.
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/>'))
})
}
)
)
Note you need to use <br/>
as a line break. Also the text you wish to display needs to be HTML escaped so use the HTML
function.
Solution 2:
According to Joe Cheng:
Uhhh I don't recommend using
renderUI
andhtmlOutput
[in the way that is explained in the other answer]. You are taking text that is fundamentally text, and coercing to HTML without escaping (meaning if the text just happens to include a string that contains special HTML characters, it could be parsed incorrectly).How about this instead:
textOutput("foo"),
tags$style(type="text/css", "#foo {white-space: pre-wrap;}")
(Replace the foo in #foo with the ID of your textOutput)