[R] Operating on windows of data

Gabor Grothendieck ggrothendieck at myway.com
Mon Mar 22 07:39:28 CET 2004



You can retain the trick of using subset and still get
rid of the loop in:

   http://www.mayin.org/ajayshah/KB/R/EXAMPLES/rollingreg.R

by using sapply like this (untested):

dat <- sapply( seq(T-width), function(i) {
    model <- lm(dlinrchf ~ dlusdchf + dljpychf + dldemchf, A, 
                i:(i+width-1))
    details <- summary.lm(model)
    tmp <- coefficients(model)
    c( USD = tmp[2], JPY = tmp[3], DEM = tmp[4], 
           R2 = details$r.squared, RMSE = details$sigma )
} )
dat <- as.data.frame(t(dat))
attach(dat)


Date:   Mon, 22 Mar 2004 10:28:45 +0530 
From:   Ajay Shah <ajayshah at mayin.org>
To:   <sdavis2 at mail.nih.gov>, <r-help at stat.math.ethz.ch> 
Subject:   Re: [R] Operating on windows of data 

 
> I have a data set that is comprised of, for simplicity, a vector of
> numbers that I want to march across+in overlapping windows of say 10
> values each, computing a couple of values for each window. Is there
> +a vectorized way to do this, or do I truly need to resort to
> looping--I think so? Any other clever thoughts?

I'm not sure this is clever, but I use the subset capabilities of
R. See

http://www.mayin.org/ajayshah/KB/R/ols.html

3 of the examples there are related to your question, though it's
still using loops. :-)

-- 
Ajay Shah Consultant
ajayshah at mayin.org Department of Economic Affairs
http://www.mayin.org/ajayshah Ministry of Finance, New Delhi




More information about the R-help mailing list