0% found this document useful (0 votes)
30 views5 pages

Introduction To The R Language Introduction To The R Language

This document introduces the tapply function in R which applies a function over subsets of a vector. Tapply takes a vector X, an index factor or list of factors INDEX, and a function FUN to apply. It returns the result of applying FUN to each group defined by INDEX. Examples show using tapply to calculate group means of a vector grouped by a factor, both with and without simplification, as well as using it to find the range of values within each group.

Uploaded by

Augusto Ferrari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views5 pages

Introduction To The R Language Introduction To The R Language

This document introduces the tapply function in R which applies a function over subsets of a vector. Tapply takes a vector X, an index factor or list of factors INDEX, and a function FUN to apply. It returns the result of applying FUN to each group defined by INDEX. Examples show using tapply to calculate group means of a vector grouped by a factor, both with and without simplification, as well as using it to find the range of values within each group.

Uploaded by

Augusto Ferrari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Introduction to the R Language Introduction to the R Language

Loop Functions - tapply


Roger Peng, Associate Professor
Johns Hopkins Bloomberg School of Public Health
tapply tapply
tapply is used to apply a function over subsets of a vector. I dont know why its called tapply.
> str(tapply)
function (X, INDEX, FUN = NULL, ..., simplify = TRUE)
X is a vector
INDEX is a factor or a list of factors (or else they are coerced to factors)
FUN is a function to be applied
... contains other arguments to be passed FUN
simplify, should we simplify the result?

2/14
tapply tapply
Take group means.
> x <- c(rnorm(10), runif(10), rnorm(10, 1))
> f <- gl(3, 10)
> f
[1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3
[24] 3 3 3 3 3 3 3
Levels: 1 2 3
> tapply(x, f, mean)
1 2 3
0.1144464 0.5163468 1.2463678
3/14
tapply tapply
Take group means without simplication.
> tapply(x, f, mean, simplify = FALSE)
$1
[1] 0.1144464
$2
[1] 0.5163468
$3
[1] 1.246368
4/14
tapply tapply
Find group ranges.
> tapply(x, f, range)
$1
[1] -1.097309 2.694970
$2
[1] 0.09479023 0.79107293
$3
[1] 0.4717443 2.5887025
5/14

You might also like