You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shiny中对齐checkboxGroupInput与renderText输出?

Fix Indentation Issue in Shiny's verbatimTextOutput When Multiple Checkboxes Are Selected

Hey there! I get it—spending weeks stuck on a tiny formatting bug can be so frustrating. Let’s fix that indentation problem in your Shiny app right away.

The Root Cause

Your current code uses paste(" You have chosen : ", input$Analysis,"\n"), which returns a vector of strings when multiple checkboxes are selected (one string per chosen option). When renderText passes this vector to verbatimTextOutput, the widget automatically indents every line after the first one by default—this is what’s causing your misalignment.

The Fix

Instead of returning a vector, we’ll combine all lines into a single string using collapse = "\n". This tells Shiny to render everything as one block of text, with no automatic indentation. Here’s the adjusted code:

library(shiny)
ui <- fluidPage(
  pageWithSidebar(
    headerPanel("Analysis"),
    sidebarPanel(
      titlePanel(title = " Options "),
      checkboxGroupInput("Analysis", label = h3("Analysis"), choices = list("HM", "Palyno", "Pesticides"), selected = NULL)
    ),
    mainPanel(
      h3("Analysis"),  # Added h3 to match your sidebar header style (optional tweak)
      verbatimTextOutput("MyAnalysis")
    )
  )
)
server <- function(input, output) {
  output$MyAnalysis <- renderText({
    # Handle empty selection with a friendly message
    if (is.null(input$Analysis) || length(input$Analysis) == 0) {
      "No analysis options selected yet."
    } else {
      # Create a full line for each selected option, then merge into one string
      lines <- paste("You have chosen :", input$Analysis)
      paste(lines, collapse = "\n")
    }
  })
}
shinyApp(ui, server)

What Changed?

  1. We added a check for empty selections to avoid blank output and give users clear feedback.
  2. We generate a complete line for each selected option using paste("You have chosen :", input$Analysis).
  3. We use paste(..., collapse = "\n") to merge all lines into a single string, which eliminates the automatic indentation.

Now when you select multiple options, your output will be clean and perfectly aligned:

You have chosen : HM
You have chosen : Palyno
You have chosen : Pesticides

内容的提问来源于stack exchange,提问作者Sacha Van Hauwaert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:18:29