You can also do the regressions "in parallel" as follows: x = -25:25 y = 0.05*x^2 + 2* x - 4 y1 = y + rcauchy(51) y2 = y + rcauchy(51)^2 y3 = y/10 - 5 + rnorm(51)
Y = cbind(y, y1, y2, y3) m = lm(Y~x) print(coef(m)) Hope this helps, Michael On Fri, Sep 16, 2011 at 3:37 PM, Luke Miller <mille...@gmail.com> wrote: > Create an output vector to hold your slopes before starting the loop, then > use your index i to place each new slope in the appropriate position in > your > vector. > > y1<-rnorm(100, mean=0.01, sd=0.001) > y2<-rnorm(100, mean=0.1, sd=0.01) > > x<-(c(10,400)) > > my.slopes = vector("numeric",100) # initialize a numeric vector, length > 100, filled with zeros initially > > for (i in 1:100) { > > #create the linear model for each data set > model1<-lm(c(y1[i],y2[i])~x) > slope1<-model1$coefficients[2] > my.slopes[i] = slope1 # stick each new slope value into my.slopes[i] > } > > You could skip the slope1 <- model1$coefficients[2] step and just put the > slope directly into my.slopes[i] as well. > > On Fri, Sep 16, 2011 at 3:25 PM, <beaulieu.j...@epamail.epa.gov> wrote: > > > Hello, > > > > I would like to write a loop to 1) run 100 linear regressions, and 2) > > compile the slopes of all regression into one vector. Sample input data > > are: > > > > y1<-rnorm(100, mean=0.01, sd=0.001) > > y2<-rnorm(100, mean=0.1, sd=0.01) > > > > x<-(c(10,400)) > > > > #I have gotten this far with the loop > > > > for (i in 1:100) { > > > > #create the linear model for each data set > > model1<-lm(c(y1[i],y2[i])~x) > > slope1<-model1$coefficients[2] > > } > > > > How can I compile the slopes from all 100 regressions into one vector? > > > > Thanks, > > Jake > > [[alternative HTML version deleted]] > > > > ______________________________________________ > > R-help@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. > > > > > > -- > ___________________________ > Luke Miller > Postdoctoral Researcher > Marine Science Center > Northeastern University > Nahant, MA > (781) 581-7370 x318 > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help@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. > [[alternative HTML version deleted]] ______________________________________________ R-help@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.