[R] Function apply

arun smartpink111 at yahoo.com
Tue Jul 23 16:48:36 CEST 2013


Hi,
Try:
set.seed(25)
X<- matrix(sample(1:50,3*140,replace=TRUE),nrow=140)
#either
res1<-do.call(rbind,lapply(split(as.data.frame(X),((seq_len(nrow(X))-1)%/%10)+1),function(x) apply(x,2,mean)))
#or
 res2<-t(sapply(split(as.data.frame(X),((seq_len(nrow(X))-1)%/%10)+1),colMeans))
 identical(res1,res2)
#[1] TRUE

#orlibrary(itertools)
it<-ihasNext(isplitRows(X,chunkSize=10))
 while(hasNext(it)){
 print( apply(nextElem(it),2,mean))
 }
#[1] 23.4 29.1 31.5
#[1] 28.2 21.8 17.2
#[1] 14.3 24.3 36.4
#[1] 22.2 25.2 24.2
#[1] 28.5 22.6 27.3
#[1] 19.6 25.6 20.0
#[1] 25.7 16.3 27.9
#[1] 20.0 24.8 26.7
#[1] 26.3 30.0 33.0
#[1] 21.9 24.0 32.3
#[1] 25.6 27.2 34.4
#[1] 13.7 30.2 16.7
#[1] 23.2 27.0 25.3
#[1] 26.4 28.6 25.2

 head(res1)
#    V1   V2   V3
#1 23.4 29.1 31.5
#2 28.2 21.8 17.2
#3 14.3 24.3 36.4
#4 22.2 25.2 24.2
#5 28.5 22.6 27.3
#6 19.6 25.6 20.0

A.K.



Dear, 
I have a matrix with 140 rows. With the following code, I can calculate the mean of each column. 
> X <- matrix 
> apply(X,MARGIN=2,FUN=mean) 
But, how to calculate the mean of each 10 rows? 
Thank you at advance.  



More information about the R-help mailing list