next up previous
Next: Bulletproofing Up: Programming in S-PLUS1 Previous: Loops and Logic

Apply

When you have time and memory constraints, the function apply is often more useful than a loop. Consider the iris data set (included with S-PLUS) which consists of 50 observations of four characteristics of three types of iris. To find the mean observation for each characteristic, one possibility is:

> get.iris.mean <- function(x)
+ {
+ report <- rep(0,4)
+ for(i in 1:4)
+ report[i] <- mean(iris[,i,])
+ report
+ }
> get.iris.mean(iris)
[1] 5.843333 3.057333 3.758000 1.199333
A cleaner way, which does not involve any looping, is:

> apply(iris, 2, mean)
 Sepal L. Sepal W. Petal L. Petal W.
 5.843333 3.057333    3.758 1.199333
The above says ``with the matrix iris, along margin 2 apply the function mean''.

To find the mean for each characteristic (margin 2) for each type of iris, use:

> apply(iris, c(2,3), mean)
         Setosa Versicolor Virginica
Sepal L.  5.006      5.936     6.588
Sepal W.  3.428      2.770     2.974
Petal L.  1.462      4.260     5.552
Petal W.  0.246      1.326     2.026



Brian Junker 2002-08-26