R/agg.wtd.mean.R

Defines functions agg.wtd.mean

Documented in agg.wtd.mean

agg.wtd.mean <- function(x, by, weights = NULL, na.rm = FALSE) {
  if(is.null(weights)) weights <- rep(1, nrow(data.frame(x)))
  res <- split(data.frame(weights,x), by)
  if(ncol(res[[1]])==2) {
    res <- data.frame(mean = sapply(res, function(z) stats::weighted.mean(z[,2], z[,1], na.rm = na.rm)))
  } else {
    res <- do.call("rbind.data.frame", args = lapply(res, function(z) sapply(z[,-1], stats::weighted.mean, w = z[,1], na.rm = na.rm)))
    colnames(res) <- colnames(x)
    rownames(res) <- levels(by)
  }
  return(res)
}

Try the descriptio package in your browser

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

descriptio documentation built on Sept. 9, 2025, 5:51 p.m.