Folks, I asked a question on this mailing list about the subset support of lm(). In a flash, I got three helpful responses from Rajarshi Guha <rxg218 at psu.edu> <http://jijo.cjb.net> Erin Hodgess <hodgess at gator.uhd.edu> and Peter Dalgaard <p.dalgaard at biostat.ku.dk> :-) and it was just great. The mistake I was making was in not understanding the notion of a `subset'. I was thinking that if I have 10 observations, and I want to only use observations 3,5,7, then I have to pass in a subset vector which looks like (0,0,1,0,1,0,1,0,0,0). Nowhere does it say this, but I jumped to this conclusion (it sortof looked reasonable to me). The correct thing is to just pass a vector containing 3,5,7. Examples of working code which do this are at http://www.mayin.org/ajayshah/KB/R/ols.html I tried to carry this forward into a program which does `rolling regressions', and I got stuck. I am trying to write a program where I walk over 100 obs, doing a regression of a "moving window" of 25 obs at a time. The first regression runs over 1..25, the second from 2..26, etc. I want to make a vector of 75 different slopes obtained thusly. My code is: --------------------------------------------------------------------------- A <- read.table(file="datafile.2", col.names=c("date","dlinrchf","dlusdchf","dljpychf","dldemchf")) # The file datafile.2 has 100 observations. I want window width of 25. T=100 width=25 # Embark on the loop that will do rolling windows across the dataset. # Will build up a vector `beta' (of 75 elems) in the process. for (i in 1:T-width) { model <- lm(dlinrchf ~ dlusdchf + dljpychf + dldemchf, A, i:i+25) tmp <- coefficients(model) beta[i] = tmp[2] } summary(beta) --------------------------------------------------------------------------- I get the error -- Error in "[<-"(`*tmp*`, i, value = tmp[2]) : object is not subsetable Execution halted I am quite stuck. I know for sure that the n1:n2 type notation works for supplying a set. But when I use 'i' in it, it breaks. Could you suggest what I should do? I am very new to R and so I might be missing out on very basic things. But I am unable to understand why this program does not print out the numbers from 1 to 10: for (i in 1:10) { i } Confused, -ans. -- Ajay Shah Consultant ajayshah at mayin.org Department of Economic Affairs http://www.mayin.org/ajayshah Ministry of Finance, New Delhi
Ole F. Christensen
2004-Feb-09 13:10 UTC
[R] Subset function of lm(); "rolling regressions"
You need brackets in i:(i+25) 3:3+25 is not want you 3:(3+25) is what you want. to explicitly print out values in a for loop you need to use print for (i in 1:10) { print(i) } Ole -- Ole F. Christensen Center for Bioinformatik Aarhus Universitet Ny Munkegade, Bygning 540 8000 Aarhus C