tapply overview
The documentation definition for tapply may not seem clear the first time that you read it, because the arguments are (X, INDEX, FUN), where X is an object where the split function applies, INDEX is a factor by which X is grouped, and FUN is function as before.
To simplify this definition, we can say tapply applies FUN to X when X is grouped by INDEX. Consider the following: we have a grades data.frame that contains information for grade, year, and sex for several students. We can use tapply to get the average grade by year in a simple way.
An small example with only 10 rows of data should help:
grades
grade year sex 1 100 junior M 2 99 sophomore F 3 75 sophomore M 4 74 sophomore M 5 44 senior F 6 69 junior M 7 88 junior F 8 99 senior <NA> 9 90 firstyear M 10 92 junior F
The solution is given below.
tapply(grades$grade, grades$year, mean)
firstyear junior senior sophomore 90.00000 87.25000 71.50000 82.66667