[R] Summing over intervals

Eik Vettorazzi E.Vettorazzi at uke.uni-hamburg.de
Thu Jul 15 14:58:30 CEST 2010


Hi Steven,
how about this (using simple matrix algebra)

wind<-5 #size of window to be aggregated
if (ncol(m)%%wind!=0) stop('dimension of m does not fit')  #crude check

tmat<-apply(diag(ncol(m)/wind),1,function(x)rep(x,each=wind))/wind
m%*%tmat

hth.

Am 15.07.2010 11:39, schrieb steven mosher:
> Given a matrix of MxN
>   want to take the means of rows in the following fashion
> m<-matrix(seq(1,80),ncol=20, nrow=4)
>  result<-matrix(NA,nrow=4,ncol=20/5)
>  result[,1]<-apply(m[,1:5],1,mean)
>  result[,2]<-apply(m[,6:10],1,mean)
>  result[,3]<-apply(m[,11:15],1,mean)
>  result[,4]<-apply(m[,16:20],1,mean)
>  result
>      [,1] [,2] [,3] [,4]
> [1,]    9   29   49   69
> [2,]   10   30   50   70
> [3,]   11   31   51   71
> [4,]   12   32   52   72
>
> So, I want the mean of every successive 5 values in a row
>
> as the dimension in columns is wide I cant write it with multiple apply as
> above
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>   

-- 
Eik Vettorazzi
Institut für Medizinische Biometrie und Epidemiologie
Universitätsklinikum Hamburg-Eppendorf

Martinistr. 52
20246 Hamburg

T ++49/40/7410-58243
F ++49/40/7410-57790



More information about the R-help mailing list