拟合平滑曲线:复选框输入
与文本和数值输入不同,复选框输入只有两个可能的值:TRUE 或 FALSE。当用户勾选复选框时,输入值为 TRUE;若未勾选,则返回 FALSE。
请注意,checkboxInput() 函数中的 value 参数用于设置初始值,只能设为 TRUE 或 FALSE。
上一个练习的 Shiny 应用代码已做少量修改提供给您。现在,renderPlot() 中的 ggplot 图对象被赋给变量 p。
本练习是课程的一部分
案例研究:使用 R 的 Shiny 构建 Web 应用
练习说明
您的任务是添加一个复选框输入。勾选后,它会在图中添加一条最佳拟合线。具体要求:
- 在 UI 中添加一个复选框输入,ID 为 "fit",标签为 "Add line of best fit",初始状态为未选中。
- 在服务器端添加代码,使当该输入被勾选时,在图中添加最佳拟合线。添加最佳拟合线的代码已提供(第 26 行)。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Define UI for the application
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
textInput("title", "Title", "GDP vs life exp"),
numericInput("size", "Point size", 1, 1),
# Add a checkbox for line of best fit
___
),
mainPanel(
plotOutput("plot")
)
)
)
# Define the server logic
server <- function(input, output) {
output$plot <- renderPlot({
p <- ggplot(gapminder, aes(gdpPercap, lifeExp)) +
geom_point(size = input$size) +
scale_x_log10() +
ggtitle(input$title)
# When the "fit" checkbox is checked, add a line
# of best fit
if (___) {
p <- p + geom_smooth(method = "lm")
}
p
})
}
# Run the application
shinyApp(ui = ui, server = server)