fapply: Apply summary functions over list or vector

View source: R/zxx.R

fapplyR Documentation

Apply summary functions over list or vector

Description

fapply applies summary function(s) over a vector, list, or data frame, and fapply_by applies summary function(s) over subsets of a data frame.

Usage

fapply(data, ...)

fapply_by(formula, data, ...)

Arguments

data

for fapply, a vector, list, or data frame to operate on; for fapply_by, a data frame containing the variables in formula

...

summary function(s) such as length(.) or mean(., na.rm = TRUE) to apply; names are not required but strongly recommended

formula

a formula such as y ~ x or cbind(y1, y2) ~ x1 + x2 where the y variables are numeric data to be split into groups according to the grouping x variables, usually factors

Examples

tmp <- replace(mtcars, mtcars == 6, NA)
fapply(tmp, mean = mean(.), median = median(., na.rm = TRUE))
fapply(mtcars$mpg, mean = mean(.))

## define a new function
ci <- function(x) {
  q <- quantile(x, c(0.025, 0.975), na.rm = TRUE)
  sprintf('%.0f (%.2f, %.2f)', median(x), q[1], q[2] )
}
fapply(mtcars, median(.), '95% CI' = ci(.))

## compare: 
t(fapply(mtcars, min(.), mean(.), max(.), length(.)))
summary(mtcars)


fapply_by(mpg ~ vs + am, mtcars, mean(.), median(.), length(.))
fapply_by(as.matrix(mtcars) ~ vs, mtcars, mean = mean(.))

## one ~ one, one ~ many, many ~ one, and many ~ many
fapply_by(disp ~ cyl, mtcars, mean = mean(.))
fapply_by(disp ~ cyl + vs, mtcars, mean = mean(.))
fapply_by(cbind(disp, wt) ~ cyl, mtcars, mean = mean(.))
fapply_by(cbind(disp, wt) ~ cyl + vs, mtcars, mean = mean(.), n = length(.))

## compare
aggregate(cbind(disp, wt) ~ cyl + vs, mtcars, function(x)
  c(mean(x), length(x)))


raredd/rawr documentation built on March 4, 2024, 1:36 a.m.