# R 中的 ave 函数

### 战立侃 · 2018-06-15

1. ave 函数的论元
## function (x, ..., FUN = mean)
## NULL
• x, 需要分析的数据

• ..., 用于分组的数据，如果空缺，则把函数应用于全部数据

• FUN, 应用于数据 x 的函数。

1. 一个例子
Score <- data.frame(
RRR = c(2, 3,  8,  6,  5,  6),
RPQ = c(5, 9, 10, 13,  8,  9),
RCQ = c(8, 6, 12, 11, 11, 12)
)
Score_long <- reshape(Score, direction = "long",
varying = list(names(Score)[1:3]),
timevar = "Condition", times = colnames(Score), v.names = "Score")
Score_long <- Score_long[, names(Score_long) != "id"]
row.names(Score_long) <- NULL
Score_long $Group_Mean <- ave(Score_long$ Score, Score_long $Condition) Score_long$ Grand_Mean <- ave(Score_long $Score) Score_long ## Condition Score Group_Mean Grand_Mean ## 1 RRR 2 5 8 ## 2 RRR 3 5 8 ## 3 RRR 8 5 8 ## 4 RRR 6 5 8 ## 5 RRR 5 5 8 ## 6 RRR 6 5 8 ## 7 RPQ 5 9 8 ## 8 RPQ 9 9 8 ## 9 RPQ 10 9 8 ## 10 RPQ 13 9 8 ## 11 RPQ 8 9 8 ## 12 RPQ 9 9 8 ## 13 RCQ 8 10 8 ## 14 RCQ 6 10 8 ## 15 RCQ 12 10 8 ## 16 RCQ 11 10 8 ## 17 RCQ 11 10 8 ## 18 RCQ 12 10 8 SS_within <- sum((Score_long$ Score - Score_long $Group_Mean) ^ 2) SS_between <- sum((Score_long$ Group_Mean - Score_long $Grand_Mean) ^ 2) SS_total <- sum((Score_long$ Score - Score_long \$ Grand_Mean) ^ 2)
c(SS_total, SS_between, SS_within)
##  172  84  88
1. ave 函数的源代码
## function (x, ..., FUN = mean)
## {
##     if (missing(...))
##         x[] <- FUN(x)
##     else {
##         g <- interaction(...)
##         split(x, g) <- lapply(split(x, g), FUN)
##     }
##     x
## }
## <environment: namespace:stats>
1. ave 函数的说明文档
## Group Averages Over Level Combinations of Factors
##
## Description:
##
##      Subsets of 'x[]' are averaged, where each subset consist of those
##      observations with the same factor levels.
##
## Usage:
##
##      ave(x, ..., FUN = mean)
##
## Arguments:
##
##        x: A numeric.
##
##      ...: Grouping variables, typically factors, all of the same
##           'length' as 'x'.
##
##      FUN: Function to apply for each factor level combination.
##
## Value:
##
##      A numeric vector, say 'y' of length 'length(x)'.  If '...' is 'g1,
##      g2', e.g., 'y[i]' is equal to 'FUN(x[j]', for all 'j' with 'g1[j]
##      == g1[i]' and 'g2[j] == g2[i])'.
##
##
##      'mean', 'median'.
##
## 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()
##