Showing posts with label tapply. Show all posts
Showing posts with label tapply. Show all posts

Monday, April 5, 2010

R: replacing for loop by apply

The function "apply" in R can help to save a lot computational time when it is replacing for loops. The following is just an example illustrating this point.

time1=proc.time()
I=50;B=50;x=matrix(0,nrow=I,ncol=B);
for (i in 1:I){
for (b in 1:B){ x=matrix(rnorm(2500),nrow=50); eigen(x) }
}
time1=proc.time()-time1

time2=proc.time()
I=matrix(1:50,nrow=1); B=matrix(1:50,nrow=1);
eig2<-function(x1=1){
x=matrix(rnorm(2500),nrow=50);
eigen(x);
}
eig1<-function(x2=1){apply(B,1,eig2); }
apply(I,1,eig1);time2=proc.time()-time2
time1time2

#> time1
# user system elapsed
# 20.62 0.11 20.97
#> time2
# user system elapsed
# 0.07 0.11 0.17

Sunday, April 4, 2010

tapply for aggregate statistics

The use of apply function can avoid a for loop and it leads to faster computing. This example is about how to use tapply to compute some group/aggregated statistics.

Use tapply for most basic by processing (By processing = Aggregate statistics = stratified estimates; statistics computedafter cross-classifying data)

> y <- 1:8
> sex <-c(rep(’male’,4),rep(’female’,4))
> treat <-rep(c(’A’,’B’),4)
> sex
[1] "male" "male" "male" "male" "female" "female" "female" "female"
> treat
[1] "A" "B" "A" "B" "A" "B" "A" "B"
> tapply(y, sex, mean)
female male
6.5 2.5
> tapply(y, treat, mean)
A B
4 5
> tapply(y, list(sex,treat), mean)
A B
female 6 7
male 2 3