在 Shiny 里,UI (User Interface) 决定了你的网页长什么样。 你可以加入各种输入控件(用户提供数据),和输出控件(显示结果)。
常用输入控件(Input Widgets)
| 函数 | 说明 | 示例 |
|---|---|---|
textInput() |
文本输入框 | 输入名字、评论 |
numericInput() |
数字输入框 | 输入年龄、数量 |
sliderInput() |
滑动条 | 选择数值区间 |
selectInput() |
下拉菜单 | 选择股票代码、国家 |
radioButtons() |
单选按钮 | 选择性别、Yes/No |
checkboxInput() |
单个复选框 | 勾选选项 |
checkboxGroupInput() |
多个复选框 | 选择多个爱好 |
actionButton() |
按钮 | 点击执行操作 |
常用输出控件(Output Widgets)
| 函数 | 说明 | 示例 |
|---|---|---|
textOutput() |
显示文字 | 输出用户输入 |
verbatimTextOutput() |
显示原始文字(代码格式) | 显示 R 结果 |
tableOutput() |
显示表格 | iris 数据 |
plotOutput() |
显示图表 | 绘制 ggplot 图 |
多种输入 + 输出
library(shiny)
ui <- fluidPage(
titlePanel("Day 2: Shiny UI 基础"),
sidebarLayout(
sidebarPanel(
textInput("name", "请输入你的名字:", "小明"),
numericInput("age", "请输入你的年龄:", 20, min = 1, max = 100),
selectInput("color", "选择你最喜欢的颜色:",
choices = c("红色", "蓝色", "绿色")),
radioButtons("gender", "性别:", choices = c("男", "女")),
checkboxGroupInput("hobby", "选择你的爱好:",
choices = c("运动", "音乐", "旅行", "阅读")),
actionButton("go", "提交")
),
mainPanel(
h3("结果:"),
textOutput("intro")
)
)
)
server <- function(input, output) {
output$intro <- renderText({
paste("大家好,我是", input$name,
",今年", input$age, "岁。",
"我是", input$gender, "生,",
"喜欢的颜色是", input$color, ",",
"爱好有:", paste(input$hobby, collapse = "、"))
})
}
shinyApp(ui, server)