R/leaflet.R

Defines functions eq_map eq_create_label

Documented in eq_create_label eq_map

#' Visualize Earthquakes on Earth map
#'
#' Visualizes earthquakes data using `leaflet` package
#'
#' @param data Data frame containing the filtered data with earthquakes
#' @param annot_col Name of the column containing annotation text
#'
#' @return Leaflet map widget
#'
#' @examples
#' \dontrun{
#' data(earthquakes)
#' eq_clean_data(earthquakes) %>%
#' eq_location_clean() %>%
#' dplyr::filter(COUNTRY == "MEXICO" & lubridate::year(DATE) >= 2000) %>%
#' eq_map(annot_col = "DATE")
#' }
#'
#' @importFrom dplyr %>% rename
#' @importFrom tidyselect one_of
#' @importFrom leaflet leaflet addTiles addCircleMarkers
#'
#' @export
eq_map <- function(data, annot_col = "DATE") {
  data %>%
    dplyr::rename(popup_text = tidyselect::one_of(annot_col)) %>%
    leaflet::leaflet() %>%
    leaflet::addTiles() %>%
    leaflet::addCircleMarkers(
      lng = ~ LONGITUDE,
      lat = ~ LATITUDE,
      radius = ~ EQ_PRIMARY,
      popup = ~ popup_text,
      weight = 1
    )
}

#' Creates an HTML label that can be used as the annotation text in the leaflet map
#'
#' Helper function that creates a label column based on other columns' values
#'
#' @param data Data frame containing the filtered data with earthquakes
#' @param label_col Name of the column that will contain annotation text
#'
#' @return data frame
#'
#' @examples
#' \dontrun{
#' data(earthquakes)
#' eq_clean_data(earthquakes) %>%
#' eq_location_clean() %>%
#' dplyr::filter(COUNTRY == "MEXICO" & lubridate::year(DATE) >= 2000) %>%
#' eq_create_label(label_col = "popup_text") %>%
#' eq_map(annot_col = "popup_text")
#' }
#'
#' @importFrom dplyr %>% mutate pull
#'
#' @export
eq_create_label <- function(data, label_col = "label_text") {
  data %>%
    dplyr::mutate(!!label_col :=
                    ifelse(is.na(LOCATION_NAME), "",
                           paste0("<b>Location: </b>",
                                  LOCATION_NAME,
                                  "<br>")
                    )
    ) %>%
    dplyr::mutate(!!label_col := paste0(dplyr::pull(., label_col),
                                        ifelse(is.na(EQ_PRIMARY), "",
                                               paste0("<b>Magnitude: </b>",
                                                      EQ_PRIMARY,
                                                      "<br>")
                                        ))
    ) %>%
    dplyr::mutate(!!label_col := paste0(dplyr::pull(., label_col),
                                        ifelse(is.na(TOTAL_DEATHS), "",
                                               paste0("<b>Total deaths: </b>",
                                                      TOTAL_DEATHS)
                                        ))
    )
}
avidclam/msdr5 documentation built on May 29, 2019, 11:02 p.m.