R/round_numeric_cols.R

Defines functions round_numeric_cols

Documented in round_numeric_cols

#' Round all numeric type columns in a data frame
#'
#' Automatically applies `round()` to all numeric columns in a data frame
#' using `dplyr::mutate_all()`. Column names are retained, the number of
#' digits rounded to defaults to zero.
#'
#' @param .tbl a tibble or data frame
#' @param .digits integer indicating the number of decimal places to be used.
#'     See `?round` for more information.
#'
#' @return a tibble or data frame whose numeric columns are rounded
#' @export
#'
#' @examples
#' library(dplyr)
#'
#' set.seed(1914)
#'
#' example_tbl <- tibble(
#'   col_one   = runif(n = 10) * 100,
#'   col_two   = runif(n = 10) * 50,
#'   col_three = rep(c("a", "b", "c", "d", "e"), times = 2)
#' )
#'
#' example_tbl
#'
#' example_tbl %>% round_numeric_cols()
round_numeric_cols <- function(.tbl, .digits = 0) {

  dplyr::mutate_if(
    .tbl       = .tbl,
    .predicate = is.numeric,
    .funs      = round,
    digits     = .digits
  )

}
RobbyLankford/lankford documentation built on April 24, 2020, 7:37 p.m.