R/corr_map.R

Defines functions corr_map

Documented in corr_map

#' Title
#'
#' @param df data frame object for the correlation map
#' @param columns character vector of columns to  generate correlation map from
#'
#' @return the correlation map plot based on the given (numeric) columns
#' @export
#'
#' @importFrom stats cor
#'
#' @examples
#' library(palmerpenguins)
#' plots_list <- corr_map(penguins, c('body_mass_g', 'flipper_length_mm'))
#' plots_list
corr_map <- function(df, columns) {
  if (!is.data.frame(df)) {
    stop("Expecting a data frame for df parameter in corr_map")
  }
  if (!is.character(columns)) {
    stop("Expecting a character vector for columns parameter in corr_map")
  }

  for (col in columns) {
    if (!(col %in% colnames(df))) {
      stop(paste("Column:", col, "does not exist in the given df"))
    }
  }

  selected_df <- df[columns] |>
    dplyr::select_if(is.numeric)

  if (ncol(selected_df) == 0) {
    stop("None of the columns is numeric")
  }

  selected_df |>
    cor(method = "spearman", use = "complete.obs") |>
    data.frame() |>
    as.data.frame() |>
    tibble::rownames_to_column() |>
    tidyr::pivot_longer(-rowname) |>
    ggplot2::ggplot() +
    ggplot2::aes(x = rowname,
                 y = name,
                 fill = value) +
    ggplot2::geom_tile() +
    ggplot2::scale_fill_distiller(palette = 'PuOr', limits = c(-1, 1)) +
    ggplot2::theme(
      axis.title.x = ggplot2::element_blank(),
      axis.title.y = ggplot2::element_blank()
    )
}
UBC-MDS/slimreda documentation built on Feb. 7, 2022, 9:12 a.m.