[R] sliding window over a large vector

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Tue Dec 16 09:24:45 CET 2008


you can have a look at the rollapply() function in the zoo package, e.g.,

x <- rbinom(100, 1, 0.5)
z <- zoo(x)
rollapply(z, 3, sum)


I hope it helps.

Best,
Dimitris


Chris Oldmeadow wrote:
> Hi all,
> 
> I have a very large binary vector, I wish to calculate the number of 
> 1's  over sliding windows.
> 
> this is my very slow function
> 
> slide<-function(seq,window){
>   n<-length(seq)-window
>   tot<-c()
>   tot[1]<-sum(seq[1:window])     for (i in 2:n) {
>      tot[i]<- tot[i-1]-seq[i-1]+seq[i]
>   }
>   return(tot)
> }
> 
> this works well for for reasonably sized vectors. Does anybody know a 
> way for large vectors ( length=12 million), im trying to avoid using C.
> 
> Thanks,
> Chris
> 
> ______________________________________________
> 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.
> 

-- 
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014



More information about the R-help mailing list