rsquaredacademy / descriptr
1
#' Category wise descriptive statistics
2
#'
3
#' Descriptive statistics of a continuous variable for the combination of levels
4
#' of two or more categorical variables.
5
#'
6
#' @param data A \code{data.frame} or a \code{tibble}.
7
#' @param col Column in \code{data}; continuous variable.
8
#' @param ... Columns in \code{data}; categorical variables.
9
#'
10
#' @examples
11
#' ds_group_summary_interact(mtcarz, mpg, cyl, gear)
12
#'
13
#' @seealso \code{\link{ds_group_summary}}
14
#'
15
#' @export
16
#'
17
ds_group_summary_interact <- function(data, col, ...) {
18

19 1
  check_df(data)
20

21 1
  cvar_name <- deparse(substitute(col))
22 1
  c_var <- rlang::enquo(col)
23 1
  check_numeric(data, !! c_var, cvar_name)
24

25 1
  g_var <- rlang::quos(...)
26 1
  gdata <- dplyr::select(data, !!! g_var)
27 1
  nums  <- unlist(lapply(gdata, is.numeric))
28 1
  non_type <- colnames(gdata[nums])
29

30 1
  error_message <- paste0("Below grouping variables are not categorical: \n",
31 1
                    paste("-", non_type, collapse = "\n"))
32

33 1
  if (length(non_type) > 0) {
34 1
        stop(error_message, call. = FALSE)
35
  }
36

37 1
  cats   <- unlist(lapply(gdata, is.factor))
38 1
  cnames <- colnames(gdata[cats])
39

40 1
  data %>%
41 1
    dplyr::select(!!c_var, !!! g_var) %>%
42 1
    na.omit() %>%
43 1
    dplyr::mutate(
44 1
      Levels = interaction(!!! g_var)
45
    ) %>%
46 1
    dplyr::select(Levels, !! c_var) %>%
47 1
    dplyr::group_by(Levels) %>%
48 1
    dplyr::summarise_all(list(
49 1
      min = min, max = max, mean = mean, t_mean = trimmed_mean,
50 1
      median = median, mode = ds_mode, range = ds_range,
51 1
      variance = var, stdev = sd, skew = ds_skewness,
52 1
      kurtosis = ds_kurtosis, coeff_var = ds_cvar, q1 = quant1,
53 1
      q3 = quant3, iqrange = IQR)) %>%
54 1
    tidyr::separate(Levels, into = cnames)
55

56
}
57

Read our documentation on viewing source code .

Loading