Skip to contents

Make a function applicable to grouped data.

Usage

grouped(f, ...)

Arguments

f

A function.

...

Deprecated. Additional arguments to f that should not be treated as grouped.

Value

A function like f with a new argument group. This accepts a factor to split all other arguments in f into groups before applying f to each group and combining the results. It is similar to ave(), but more general.

See also

Other operators: balanced(), quantity_index()

Examples

p1 <- price6[[3]]
p0 <- price6[[2]]
q1 <- quantity6[[3]]
q0 <- quantity6[[2]]

# Calculate Tornqvist weights for two groups

f <- factor(rep(letters[1:2], each = 3))
tornqvist_weights <- grouped(index_weights("Tornqvist"))
tornqvist_weights(p1, p0, q1, q0, group = f)
#> [1] 0.18247009 0.33481172 0.48271819 0.12865397 0.81833234 0.05301369

# Calculate a mean like ave(), but with weights

x <- 1:6
w <- c(1:5, NA)
grouped_mean <- grouped(\(x, w) geometric_mean(x, w, na.rm = TRUE))
grouped_mean(x, w, group = f)
#> [1] 2.182247 2.182247 2.182247 4.527921 4.527921 4.527921

# Redistribute weights

w1 <- c(2, 4)
w2 <- 1:6

harmonic_mean(mapply(harmonic_mean, split(x, f), split(w2, f)), w1)
#> [1] 3.333333

wr <- grouped(scale_weights)(w2, group = f) * w1[f]
harmonic_mean(x, wr)
#> [1] 3.333333