R/top_n_number_of_variable.r

#' Top n number of variable
#'
#' @importFrom magrittr %>%
#' @param df : a data frame
#' @param groupings : vector of variable names to group by.
#' @param n : output the top n groups
#'
#' @return tibble that has n rows.
#' @export
#'
#' @examples
#' top_n_number_of_variable(mtcars,'carb',4)
#'
top_n_number_of_variable <- function(df , groupings, n=1){

  (dplyr::as_tibble(df) %>% dplyr::group_by_at(dplyr::vars(dplyr::one_of(groupings))) %>%
    dplyr::summarise(count=n()) %>% dplyr::arrange(dplyr::desc(count)))[1:n,]
}
ArithmeticR/TOmisc documentation built on May 14, 2019, 12:43 p.m.