# [R] Moving window regressions - how can I improve this code?

Warnes, Gregory R gregory_r_warnes at groton.pfizer.com
Tue Apr 27 01:03:08 CEST 2004

```movingWindow can be made even simpler when using the running() with recent
versions of the gregmisc library:

movingWindow <- function(formula, data, width, ...)
{
index <- 1:nrow(data)
running(index, fun=function(st) summary(lm(formula, data[st,])),
width=width)
}

this returns a *matrix* with one row per element of summary.  To get the
coefficients, do

movingWindow( weight ~ height, women, 5)["coefficients",]

-Greg

> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch
> [mailto:r-help-bounces at stat.math.ethz.ch]On Behalf Of Gabor
> Grothendieck
> Sent: Sunday, April 25, 2004 10:07 AM
> To: r-help at stat.math.ethz.ch
> Subject: Re: [R] Moving window regressions - how can I improve this
> code?
>
>
> Gabor Grothendieck <ggrothendieck <at> myway.com> writes:
>
> > movingWindow <- function(formula, data, width, ...) {
> >     nr <- nrow(data)
> >     width <- as.integer(width)[1]
> >     stopifnot( width > 0, width <= nr )
> >     indices <- as.data.frame( t( embed( 1:nr, width ) ) )
> >     lapply(indices, function(st) summary(lm(formula, data[st,])) )
> > }
> >
>
> Just one further simplification using apply instead of lapply to
> eliminate having to transform embed:
>
> movingWindow <- function(formula, data, width, ...) {
>     nr <- nrow(data)
>     width <- as.integer(width)[1]
>     stopifnot( width > 0, width <= nr )
>     apply( embed(1:nr, width), 1, # rows are indices of
> successive windows
> 		function(st) summary(lm(formula, data[st,])) )
> }
>
> This could also be used in movingWindow2, as well.
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help