R/mode.R

Defines functions top_n_vals mode_fn mode_pct

Documented in mode_fn mode_pct top_n_vals

#' mode with %
#'
#' returns the mode of a vector with what percent of the data is the mode
#'
#' @param x a vector
#'
#' @return a unit character vector
#' @export
#'
#' @examples
#' c("b", "b", letters) %>% mode_pct()
mode_pct <- function(x) {
  mode_fn(x) -> mode1

  calc_pct(x, mode1)

}

#' statistical mode
#'
#' returns the mode of a vector
#'
#' @param x a vector
#'
#' @return a unit vector
#' @export
#'
#' @examples
#' c("b", "b", letters) %>% mode_fn()
mode_fn <- function(x) {
  ux <- unique(x)
  ux[which.max(tabulate(match(x, ux)))]
}

#' top n vals
#'
#' @param x vector
#' @param top_n integer to specify top n modes
#'
#' @return character unit vector
#' @export
#'
#' @examples
#' tibble::tibble(x = 1:10 %>% c(10,10,10,5,5)) -> t1
#' t1 %>% top_n_vals()

top_n_vals <- function(x, top_n = 3){

  tibble::tibble(x = x) -> t1
  n <- NULL

  t1 %>%
    dplyr::add_count(x) %>%
    dplyr::arrange(dplyr::desc(n)) %>%
    dplyr::distinct(n, .keep_all = T) %>%
    dplyr::slice(1:top_n) %>%
    dplyr::pull(x) -> x1
  purrr::map(x1, .f = ~calc_pct(vec = t1$x, value = .))%>%
    unlist %>% stringr::str_c(collapse = " | ")
}




calc_pct <- function(vec, value ){
  mean(vec == value, na.rm = T) -> avg1
  (avg1 * 100) %>% round() %>% stringr::str_c("%") -> pct

  stringr::str_c(value, " ", "(", pct, ")")
}

Try the validata package in your browser

Any scripts or data that you put into this service are public.

validata documentation built on Feb. 26, 2026, 5:06 p.m.