[R] for loop and linear models

Brian Diggs diggsb at ohsu.edu
Mon Jun 20 22:17:03 CEST 2011


On 6/20/2011 12:23 PM, ivan 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.

You are overwriting the variable "models" each iteration through the 
loop.  When you return it, it only has the last model.  The most direct 
fix is to initialize it at the start of the function (models <- list()), 
and append to it in the loop (models <- append(models, etc...))

The longer answer is that this is not the best (most R-ish) way to 
approach the problem.  Consider a different algorithm: gather a list of 
the column names that are common (and for which there should be a model 
each) and then iterate over that collection creating a model for each 
one and returning that in a list.

library("plyr")

fun<- function(x,y){
	cols <- intersect(colnames(x), colnames(y))
	names(cols) <- cols
	llply(cols, function(col) {lm(ts(x[col])~ts(y[col]))})
}	

# make fake data.
# NOTE: you should have included something like this in your question.
# I made some because I'm in something like a good mood, but that
# isn't something you should count on.
X <- data.frame(matrix(rnorm(100), ncol=10))
names(X) <- LETTERS[1:10]
Y <- data.frame(matrix(rnorm(100), ncol=10))
names(Y) <- LETTERS[1:10]

fun(X,Y)


> Regards
>
> 	[[alternative HTML version deleted]]

Yeah, don't do that either.  The posting guide is your friend (or will 
at least help you get answers).


-- 
Brian S. Diggs, PhD
Senior Research Associate, Department of Surgery
Oregon Health & Science University



More information about the R-help mailing list