[R] loop for multiple regressions

From: Denise Xifara <dionysia-kiara.xifaras_at_st-hildas.ox.ac.uk>
Date: Tue, 22 Jul 2008 14:18:24 +0100


Dear all,
I have the following data in excel:

    day1 y 1 2 3 2 3 x1 0.2 0.3 0.4 0.3 0.2 x2 7 3.4 2 8 6 day2 y 2 4 3 2 2 x1 0.4 0.5 0.3 0.3 0.2 x2 7 8 9.1 6 5

I have the following problems:
first of all, when I ask R to read the file (with the package xlsReadWrite and the command read.xls) it has a problem with the fact that the left most corner is labelled the same way, so in order for it to work I need to do:

 day1

 y1
 1
 2
 3
 2
 3
 x11

 0.2
 0.3
 0.4
 0.3
 0.2

 x21
 7
 3.4
 2
 8
 6

 day2

 y2
 2
 4
 3
 2
 2
 x12

 0.4
 0.5
 0.3
 0.3
 0.2

 x22
 7
 8
 9.1
 6
 5

Next I need to do the regression y~ x1+x2, for the different days. I have converted the above data in the form of a matrix and labelled it mat. The following loop works:

results<-c(0,0,0,0,0)
for (i in c(1,5)){
results[i]<-lm(mat[i,]~mat[i+1,]+mat[i+2,])} results

And the results are:

Warning messages:
1: In results[i] <- lm(mat[i, ] ~ mat[i + 1, ] + mat[i + 2, ]) :   number of items to replace is not a multiple of replacement length 2: In results[i] <- lm(mat[i, ] ~ mat[i + 1, ] + mat[i + 2, ]) :   number of items to replace is not a multiple of replacement length
> results

[[1]]
 (Intercept) mat[i + 1, ] mat[i + 2, ]
   2.4918415 1.5151515 -0.1356220

[[2]]
[1] 0
[[3]]
[1] 0
[[4]]
[1] 0
[[5]]

 (Intercept) mat[i + 1, ] mat[i + 2, ]
  -0.3741935 3.4193548 0.2580645

The method does work but it is not ideal. The problem is that the real data that I will be using will involve regressions of 20 or so variables over 3000 days. I also want to avoid finding the exact values that i should take inside the loop.
Is there a better way of carrying out these regressions so that I do not need to relabel everything, the results are faster and it is clear and easy to isolate the results of the linear models for each day?

Thank you very much everyone in advance, Regards,
Denise

        [[alternative HTML version deleted]]



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. Received on Tue 22 Jul 2008 - 13:25:02 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 22 Jul 2008 - 13:32:06 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive