generalized_ave: Generalized ave

Description Usage Arguments Details Value Examples

View source: R/helpers.R

Description

A generalization of ave() that is easier to use with functions other than mean().

Usage

1

Arguments

fun

A function.

Details

This is a function factory that returns a function that behaves much like ave(), except that it works more consistently with functions other than mean(). The function returned by generalized_ave():

  1. Allows further (named) arguments to be passed to fun;

  2. Bases the return value off of fun, instead of x.

Unlike ave(), the names for x are the only attributes of x that are kept.

Value

A function

function(x, f, ...),

where x is a vector, f is a factor that groups x, and ... are other arguments to pass to fun.

x serves the same role as in ave(), with f replacing ... so that there is a way to pass further arguments to fun. Unlike ave(), the type of the return value is determined by the return value of fun, which may not be the same as x.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
generalized_ave(mean)(1:10, rep(1:2, 5)) # same as stats::ave(1:10, rep(1:2, 5))

generalized_ave(sum)(1:10, rep(1:2, 5)) # same as stats::ave(1:10, rep(1:2, 5), FUN = sum)

generalized_ave(function(x) x == max(x))(1:10, rep(1:2, 5)) # returns a logical

# use interaction to group by multiple factors
f <- rep(1:2, 5)
g <- rep(1:5, 2)
generalized_ave(mean)(1:10, interaction(f, g)) # same as stats::ave(1:10, f, g)

marberts/smart documentation built on March 9, 2021, 5:31 p.m.