Home > Software engineering >  how to print sampled output from actionButton on multiple lines in R Shiny
how to print sampled output from actionButton on multiple lines in R Shiny

Time:09-18

I would like to have an action button in R Shiny that samples three elements of a character variable and returns each on its own line. I have seen that htmltools can be used to break the text of the action button itself onto new lines, but I don't see an obvious way to pass such commands into the output of the button, especially when using the sample() function.

In the toy shiny app below, the actionButton prints three greek letters on one line,

alpha beta delta

I would like each sampled element to appear on its own line,

alpha
beta
delta

Below is the toy app

library(shiny)

# Define UI ----
ui <- fluidPage(
  titlePanel("Toy"),

  # Copy the line below to make an action button
  actionButton("greek", label = "Greek letters"),
  
  verbatimTextOutput("text")
)

# Define server logic ----
server <- function(input, output, session) {
  
  observeEvent(input$greek, {
    greek <- c("alpha","beta","gamma","delta")
  })
  
  observeEvent(input$greek,{
    output$text <- renderText(sample(greek,3))
  })
  
}

# Run the app ----
shinyApp(ui = ui, server = server)

CodePudding user response:

Here, try this:

library(shiny)
library(glue)

# Define UI ----
ui <- fluidPage(
  titlePanel("Toy"),

  # Copy the line below to make an action button
  actionButton("greek", label = "Greek letters"),
  verbatimTextOutput("text")
)

# Define server logic ----
server <- function(input, output, session) {
  greeks <- eventReactive(input$greek, {
    sample(c("alpha", "beta", "gamma", "delta"), size = 3)
  })

  output$text <- renderText(
    sample(greeks(), 3) |> glue_collapse(sep = "\n")
  )
}

# Run the app ----
shinyApp(ui = ui, server = server)
  • Related