开始使用免费开始使用

为应用添加结构

在 Shiny 中,布局用于通过将元素放置在指定位置来为应用添加结构。

通过 sidebarLayout() 函数创建的侧边栏布局,提供一个基础的两列结构:左侧是较窄的侧边栏,右侧是较宽的主面板。

侧边栏布局函数接收两个参数:sidebarPanel()mainPanel()。每个面板都可以包含任意组合的文本/HTML 元素,类似于在 fluidPage() 中混合这些元素的方式。

本练习是课程的一部分

案例研究:使用 R 的 Shiny 构建 Web 应用

查看课程

练习说明

您的任务是在现有应用中添加一个侧边栏布局,使输入位于左侧,输出位于主面板中。具体需要:

  • 定义 Shiny 应用的 UI。
  • 在页面中添加侧边栏布局。
  • 在布局中添加侧边栏面板,并将输入和文本放入其中。
  • 在布局中添加主面板,并将图形和表格放入其中。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Load the shiny package
library(shiny)

# Define UI for the application
ui <- ___(
  # Add a sidebar layout to the application
  ___(
    # Add a sidebar panel around the text and inputs
    ___(
      h4("Plot parameters"),
      textInput("title", "Plot title", "Car speed vs distance to stop"),
      numericInput("num", "Number of cars to show", 30, 1, nrow(cars)),
      sliderInput("size", "Point size", 1, 5, 2, 0.5)
    ),
    # Add a main panel around the plot and table
    ___(
      plotOutput("plot"),
      tableOutput("table")
    )
  )
)

# Define the server logic
server <- function(input, output) {
  output$plot <- renderPlot({
    plot(cars[1:input$num, ], main = input$title, cex = input$size)
  })
  output$table <- renderTable({
    cars[1:input$num, ]
  })
}

# Run the application
shinyApp(ui = ui, server = server)
编辑并运行代码