[R] for loop; lm() regressions; list of vectors

Uwe Ligges ligges at statistik.tu-dortmund.de
Thu Apr 1 20:45:50 CEST 2010



On 30.03.2010 20:57, David Winsemius wrote:
>
> On Mar 30, 2010, at 12:42 PM, Driss Agramelal wrote:
>
>> ## Hello everyone,
>> ##
>> ## I am trying to execute 150 times a lm regression using the 'for' loop,
>> with 150 vectors for y,
>> ##
>> ## and always the same vector for x.
>> ##
>> ## I have an object with 150 elements named "a",
>> ##
>> ## and a vector of 60 values named "b".
>> ##
>> ## Each element in "a" has 60 values plus a header.
>> ##
>> ## When I type:
>>
>> r <- lm(i ~ b)
>>
>> for(i in a) print(r)
>>
>>
>
> Try instead something like this untested modification:
>
> for(i in seq_along(a)) print(r <- lm(a[i] ~ b) )

Since a cannot be a vector, I guess you will need

for(i in seq_along(a)) print(r <- lm(a[[i]] ~ b) )

or to make the results reusable:


along <- seq_along(a)
r <- vector(mode="list", length=max(along))
for(i in along) print(r[[i]] <- lm(a[[i]] ~ b) )


Uwe Ligges



>
>>
>> ## I get 150 times the lm results of the first element of "a" regressed
>> with "b",
>> ##
>> ## whereas I would like to have 150 different regression results from
>> each
>> element in "a"...
>> ##
>> ## Can someone please help me with the syntax of my loop please?
>> ##
>> ## Many Thanks,
>> ##
>> ## Driss Agramelal
>> ##
>> ## Switzerland
>> ##
>>
>> [[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.
>
> David Winsemius, MD
> West Hartford, CT
>
> ______________________________________________
> 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