Skip to content
Snippets Groups Projects
visualize_airport_delay_dplyr.R 1.74 KiB
Newer Older
#' Visualize Mean Flight Delay by Airport
#'
#' This function visualizes the mean flight delay at each origin airport in the nycflights13 dataset.
#' It calculates the mean departure delay for each airport, joins this data with airport locations,
#' and creates a scatter plot showing mean delay as point size and color on a map of airport locations.
#'
#' @return A ggplot2 object representing the visualization of mean flight delays by airport.
#' @import dplyr
#' @import ggplot2
#' @import nycflights13
#' @param dep_delay' dep_delay
#' @param origin origin
#' @param lon lon
#' @param lat lat
#' @param mean_delay mean_dealy
#' @examples
#' # Run the function to visualize mean delays by airport:
#' visualize_airport_delays()
#' @name visualize_airport_delays
#' @export
library(dplyr)

visualize_airport_delays <- function() {
  # Join flights and airports datasets to include latitude and longitude
  airport_delays <- nycflights13::flights %>%
    dplyr::filter(!is.na(dep_delay)) %>%  # Exclude rows where departure delay is NA
    dplyr::group_by(origin) %>%  # Group by airport
    dplyr::summarize(mean_delay = mean(dep_delay, na.rm = TRUE)) %>%
    dplyr::left_join(nycflights13::airports, by = c("origin" = "faa"))  # Join with airports for lat/lon data

  # Create the ggplot2 plot
  ggplot2::ggplot(airport_delays, ggplot2::aes(x = lon, y = lat)) +
    ggplot2::geom_point(ggplot2::aes(size = mean_delay, color = mean_delay), alpha = 0.9) +
    ggplot2::scale_color_gradient(low = "blue", high = "red") +
    ggplot2::labs(
      title = "Mean Flight Delay by Airport",
      x = "Longitude",
      y = "Latitude",
      size = "Mean Delay (min)",
      color = "Mean Delay (min)"
    ) +
    ggplot2::theme_minimal()
# Call the function
visualize_airport_delays()