[R] for loop and linear models
William Dunlap
wdunlap at tibco.com
Mon Jun 20 22:13:01 CEST 2011
Your suggestion would have it return after fitting
the first model, which is not what the OP wants.
The basic problem is that
models <- list(lm(...))
replaces the old value of models with a new length-1
list. You want to add the new fitted model to the
list of fitted models. E.g.,
models <- list() # make empty list
for(...) for(...) {
models[[colnames(x)[i]]] <- lm(...) # append named element to
list
}
There are lots of other ways to do this.
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
> -----Original Message-----
> From: r-help-bounces at r-project.org
> [mailto:r-help-bounces at r-project.org] On Behalf Of Daniel Malter
> Sent: Monday, June 20, 2011 1:05 PM
> To: r-help at r-project.org
> Subject: Re: [R] for loop and linear models
>
> To be more accurate and helpful, try this:
>
> fun<- function(x,y){
> for(i in 1:length(colnames(x))){
> for(j in 1:length(colnames(y))){
> if(colnames(x)[i]==colnames(y)[j]){
> models=list(lm(ts(x[i])~ts(y[j])))
> return(models)
> }
> else{}
> }
> }
> }
>
>
> :) Does this do it for you?
> Daniel
>
>
> hazzard wrote:
> >
> > Hi,
> >
> > I have two datasets, x and y. Simplified x and y denote:
> >
> > X
> >
> > Y
> >
> > A B C A B C . . . . . . . . . . . . . . . . . .
> > I want to implement all possible models such as
> lm(X$A~Y$A), lm(X$B~Y$B),
> > lm(X$C~Y$C)... I have tried the following:
> >
> > fun<- function(x,y){
> > for(i in 1:length(colnames(x))){
> > for(j in 1:length(colnames(y))){
> > if(colnames(x)[i]==colnames(y)[j]){
> > models=list(lm(ts(x[i])~ts(y[j])))
> > }
> > else{}
> > }
> > }
> > return(models)
> > }
> >
> > The problem is that this returns only one of the three
> models, namely the
> > last one. What am I doing wrong? Thank you very much in advance.
> >
> > Regards
> >
> > [[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.
> >
>
> --
> View this message in context:
> http://r.789695.n4.nabble.com/for-loop-and-linear-models-tp361
2274p3612392.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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