54 Enhancing the Function: Towards the ‘Perfectly Formed Rear-View Mirror’

Once you have a basic function that works, you can incrementally add features to make it more robust and versatile. This could include error handling (to gracefully deal with unexpected inputs), parameters for selecting between departure and arrival delays, or options for filtering by specific airports or dates.

Let’s add the capability to choose between departure (dep_delay) and arrival (arr_delay) delays.

# Enhanced function to calculate average delay, with options for delay type and error handling
average_delay_by_airline <- function(data = flights, airline_code, delay_type = "dep_delay") {
  data %>%
    filter(carrier == airline_code) %>%
    summarise(average_delay = mean(get(delay_type), na.rm = TRUE))
}


# Test the enhanced function
average_delay_by_airline(airline_code = "AA",delay_type = "arr_delay")
#> Error in average_delay_by_airline(airline_code = "AA", delay_type = "arr_delay"): object 'flights' not found

In this version, the function now accepts an additional argument, delay_type, which allows the user to specify the type of delay they are interested in analyzing. The function checks if the provided delay_type is valid and uses dynamic column selection via get(delay_type) to compute the mean delay.