R/histogram.R

Defines functions histogram

Documented in histogram

#' Plots a histogram for a list of columns
#'
#' @param df a data frame that has columns to make histograms for
#' @param columns a character array of columns to specify which columns to generate a histogram for
#'
#' @return a list of plots where each plot is a histogram for each column in columns
#' @export
#'
#' @examples
#' library(palmerpenguins)
#' plots_list <- histogram(penguins, c('body_mass_g', 'flipper_length_mm'))
#' plots_list
#'

histogram <- function(df, columns) {
  if (!is.data.frame(df)) {
    stop("Please provide a data frame as the first argument to the function")
  }

  if (!is.character(columns)) {
    stop("Please provide a single column name or character vector")
  }

  plots_list <- list()
  for(i in seq_along(columns)) {
    column_name <- columns[[i]]
    column_name <- rlang::sym(column_name)

    if (!(columns[[i]] %in% colnames(df))) {
      stop("Column does not exist in data frame")
    }

    current_plot <- df |>
      ggplot2::ggplot(ggplot2::aes(x = !!column_name)) +
      ggplot2::geom_histogram()

    plots_list[[i]] <- current_plot
  }

  plots_list
}
UBC-MDS/slimreda documentation built on Feb. 7, 2022, 9:12 a.m.