[R] Help writing basic loop

MacQueen, Don macqueen1 at llnl.gov
Sat Sep 17 01:57:30 CEST 2011


Just a minor aside; I would have done

  my.slopes <- numeric(100)

Note that:
> class(numeric(5))
[1] "numeric"

-Don


-- 
Don MacQueen

Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
925-423-1062





On 9/16/11 12:37 PM, "Luke Miller" <millerlp at 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.Jake at 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 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.
>>
>
>
>
>-- 
>___________________________
>Luke Miller
>Postdoctoral Researcher
>Marine Science Center
>Northeastern University
>Nahant, MA
>(781) 581-7370 x318
>
>	[[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.



More information about the R-help mailing list