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

Gabor Grothendieck ggrothendieck at myway.com
Sun Apr 25 16:06:52 CEST 2004


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.




More information about the R-help mailing list