ave {stats} R Documentation

## Group Averages Over Level Combinations of Factors

### Description

A function is applied to subsets of a vector x, where each subset consists of those observations with the same factor levels. The mean function is applied by default, replacing the values in each group by the group average.

### Usage

ave(x, ..., FUN = mean)


### Arguments

 x a vector, typically numeric. ... grouping variables, typically factors, all of the same length as x. Groups are defined by the interaction of these variables. FUN a function to apply for each factor level combination. (NOTE: If given, this argument must be named.)

### Value

A vector, say y, of the same length as x. If grouping variables are missing, all elements of y are equal to FUN(x). Otherwise, if, e.g., ... is g1, g2, y[i] is equal to FUN(x[sub]) with sub comprising all j for which g1[j] == g1[i] and g2[j] == g2[i].

mean, split, tapply.

### Examples

require(graphics)

ave(1:3)  # no grouping -> grand mean

attach(warpbreaks)
ave(breaks, wool)
ave(breaks, tension)
ave(breaks, tension, FUN = function(x) mean(x, trim = 0.1))
plot(breaks, main =
"ave( Warpbreaks )  for   wool  x  tension  combinations")
lines(ave(breaks, wool, tension              ), type = "s", col = "blue")
lines(ave(breaks, wool, tension, FUN = median), type = "s", col = "green")
legend(40, 70, c("mean", "median"), lty = 1,
col = c("blue","green"), bg = "gray90")
detach()

# Running index per group
(g <- sample(c("u","s","e","R"), 24, replace = TRUE))
ave(seq_along(g), g, FUN = seq_along)


[Package stats version 4.5.0 Index]