Get startedGet started for free

Creating some helper functions

There are many elements that can be added to a shinydashboard. To allow interactions between user inputs and dashboard outputs, you need to define these interactions within the render functions that are placed in the server.

The code can become clunky very quickly if there are many interactions and many outputs. One way to get around this problem is to create your own helper functions outside of the shinydashboard environment.

In the following, you will construct two helper functions:

  1. num_listings(): Returns the no. of listings based on filtered data within a price range.
  2. make_plots(): Creates either boxplots or violin plots based on user selection, and based on filtered data within a price range.

listings is loaded, and sf, tidyverse and leaflet have been imported.

This exercise is part of the course

Building Dashboards with shinydashboard

View Course

Exercise instructions

  • Filter listings, so that it is restricted between the left and right limits of the argument range, which is a placeholder for a shinyApp input.
  • Set the correct if-else conditions so that boxplots are plotted when choice matches "Box plots", and violin plots if it's "Violin plots".

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

num_listings <- function(range){
  # Filter listings appropriately
  filter(listings, price >= ___, price <= ___) %>% nrow()
}
make_plots <- function(range, choice){
  filtered_listings <- filter(listings, price >= range[1], price <= range[2])
  # Set the correct if-else conditions
  if (choice == ___){
     filtered_listings %>%
      ggplot(aes(y = price, x = room_type)) + geom_boxplot() + theme_classic()
  }
  else if (___){
    filtered_listings %>%
      ggplot(aes(y = price, x = room_type)) + geom_violin() + theme_classic()
}}
Edit and Run Code