# 有条件地应用function

``experiment iter results A 1 30.0 A 2 23.0 A 3 33.3 B 1 313.0 B 2 323.0 B 3 350.0 ....` `

` `A sum of results (30 + 23, + 33.3) B sum of results (313 + 323 + 350)` `

`aggregate`函数在基地。

` `> aggregate(results ~ experiment, FUN=sum, data=DF) experiment results 1 A 86.3 2 B 986.0` `

` `> with(DF, tapply(results, experiment, FUN=sum)) AB 86.3 986.0` `

` `> # library(plyr) > ddply(DF[, -2], .(experiment), numcolwise(sum)) experiment results 1 A 86.3 2 B 986.0 > ## Alternative syntax > ddply(DF, .(experiment), summarize, sumResults = sum(results)) experiment sumResults 1 A 86.3 2 B 986.0` `

` `> require(dplyr) > DF %>% group_by(experiment) %>% summarise(sumResults = sum(results)) Source: local data frame [2 x 2] experiment sumResults 1 A 86.3 2 B 986.0` `

` `> with(DF, sapply(split(results, experiment), sum)) AB 86.3 986.0` `

` `> # library(data.table) > DT <- data.table(DF) > DT[, sum(results), by=experiment] experiment V1 1: A 86.3 2: B 986.0` `

` `> # library(doBy) > summaryBy(results~experiment, FUN=sum, data=DF) experiment results.sum 1 A 86.3 2 B 986.0` `

` `> (Aggregate.sums <- with(DF, by(results, experiment, sum))) experiment: A [1] 86.3 ------------------------------------------------------------------------- experiment: B [1] 986` `

` `> cbind(results=Aggregate.sums) results A 86.3 B 986.0` `

` `> library(sqldf) > sqldf("select experiment, sum(results) `sum.results` from DF group by experiment") experiment sum.results 1 A 86.3 2 B 986.0` `

`xtabs`也可以工作（只有当`FUN=sum`

` `> xtabs(results ~ experiment, data=DF) experiment AB 86.3 986.0` `