Home > OS >  Outputting multiple lines of text in R Shiny using renderUI
Outputting multiple lines of text in R Shiny using renderUI

Time:11-18

MY PROBLEM

I have a dataframe with multiple rows, each of them containing a short narrative in various sentences and a code associated to each narrative.

I'm designing a Shiny app where users select one of the narratives and they see the narrative on the main panel. I'm using htmlOutput() in the ui.R file and renderUI() in the server.R file.

My problem is that I can't find a way to get the output in multiple lines. I can only get all the sentences together, as a paragraph (like below):

"she was in Florida over the break. she went to the beach. I don't know why she did that, but she liked it. she saw a couple alligators."

However, this is what I actually want:

"she was in Florida over the break."
"she went to the beach."
"I don't know why she did that, but she liked it."
"she saw a couple alligators."
...

WHAT I TRIED

I have read that I can call the HTML() function to add a break after each sentence using paste(). But if I do that, then I get no output on the main panel when I select a narrative.

This is what I tried doing (see the HTML call at the bottom):

output$Full_text = renderUI({
    my_text = my_df %>%
      filter(narrative_code == input$selected_narrative)
      pull(narrative_text)})
    my_sentences = unlist(strsplit(my_text, "(?<=(\\.|\\?)\\s)", perl = TRUE))
    HTML(for(sentence in my_sentences){
      paste(sentence, '<br/>')})

It works when I run it in my console, but not when I run my app, so I guess the problem has to do with how to output the result.

CodePudding user response:

Use paste's collapse argument instead of the for-loop:

library(shiny)

my_sentences <- LETTERS

ui <- fluidPage(
  uiOutput("myText")
)

server <- function(input, output, session) {
  output$myText <- renderUI({
    HTML(paste0(my_sentences, collapse = "<br>"))
  })
}

shinyApp(ui, server)
  • Related