构建输出对象
在 Shiny 中构建输出有三条规则:
使用合适的
render*()函数来构建对象。将渲染函数的结果保存到服务器函数参数中的
output列表里。具体地,保存到output$<outputId>,以替换 UI 中 ID 为outputId的输出占位符。如果输出依赖任何用户修改过的输入值,您可以使用服务器函数的
input参数来访问所有输入。具体地,input$<inputId>会始终返回 ID 为inputId的输入控件的当前值。
本练习是课程的一部分
案例研究:使用 R 的 Shiny 构建 Web 应用
练习说明
给您一个 Shiny 应用,其 UI 部分已经可以正常工作。您的任务是构建所有输出。具体要求:
- 在 ID 为 "cars_plot" 的绘图输出占位符中绘制
cars数据集的图(第 23 行)。 - 在 "greeting" 文本输出中,按 "Hello NAME" 的格式渲染问候语,其中 NAME 为名称输入框的取值(第 28 行)。
- 在 "iris_table" 输出中,显示
iris数据集的前 n 行,其中 n 为数值输入框的取值(第 33 行)。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Load the shiny package
library(shiny)
# Define UI for the application
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
textInput("name", "What is your name?", "Dean"),
numericInput("num", "Number of flowers to show data for",
10, 1, nrow(iris))
),
mainPanel(
textOutput("greeting"),
plotOutput("cars_plot"),
tableOutput("iris_table")
)
)
)
# Define the server logic
server <- function(input, output) {
# Create a plot of the "cars" dataset
output$cars_plot <- render___({
plot(cars)
})
# Render a text greeting as "Hello "
output$greeting <- ___({
paste("Hello", ___)
})
# Show a table of the first n rows of the "iris" data
___ <- ___({
data <- iris[1:input$num, ]
data
})
}
# Run the application
shinyApp(ui = ui, server = server)