Fit a smooth curve: checkbox input
Unlike text and numeric inputs, checkbox inputs are limited to only two possible values: TRUE
or FALSE
. When the user checks a checkbox input, the input has a value of TRUE
, and if the box is unchecked then it returns FALSE
.
Note that the value
parameter of the checkboxInput()
function, which defines the initial value, can only be set to either TRUE
or FALSE
.
The code for the Shiny app from the last exercise is provided with some modification. The ggplot
plot object inside renderPlot()
is now assigned to a variable p
.
This exercise is part of the course
Case Studies: Building Web Applications with Shiny in R
Exercise instructions
Your task is to add a checkbox input that, when checked, will add a line of best fit to the plot. Specifically:
- Add a checkbox input to the UI with ID "fit", a label of "Add line of best fit", and an initial state of being unchecked.
- Add code to the server so that when the input is checked, a line of best fit is added to the plot. The code for adding a line of best fit is provided (line 26).
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# 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)