[R] for loop and linear models

Daniel Malter daniel at umd.edu
Mon Jun 20 22:04:37 CEST 2011


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-tp3612274p3612392.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list