R/layered_mean.R

Defines functions layered_mean

Documented in layered_mean

#' compute a mean of means
#'
#' @param x a tbl() to compute proportions
#' @param first_group_by vector of variabels names strings. the first mean would be grouped by them.
#' @param then_group_by vector of variabels names strings. the second mean would be grouped by them.
#' aought to be shorter.
#' @param value_str the variable on which to mean
#'
#' @return A tbl, grouped the same way as then_group_by with avg and n variables.
#'
#' @examples
#' cars <- mtcars %>%
#' layered_mean(value_str = "qsec",
#' first_group_by = c("vs","am","gear"),
#' then_group_by = c("vs","am"))
#'
#' @importFrom magrittr %>%
#'
#' @export


layered_mean <- function(x,first_group_by,then_group_by,value_str){

  require(tidyverse,quietly = T)

  val <- sym(value_str)
  first_group_by_list <- lapply(X = first_group_by, as.symbol)
  then_group_by_list <- lapply(X = then_group_by, as.symbol)

  avgs <- x %>%
    group_by(!!!first_group_by_list) %>%
    summarise(avg_base=mean(!!val),n=n()) %>%
    group_by(!!!then_group_by_list) %>%
    summarise(avg=weighted.mean(avg_base,w=n),n=n())


  return(avgs)


}


# example
sarid-ins/saridr documentation built on Nov. 10, 2020, 9:07 p.m.