Skip to content
Prev 263189 / 398503 Next

for loop and linear models

On 6/20/2011 12:23 PM, ivan wrote:
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)
Yeah, don't do that either.  The posting guide is your friend (or will 
at least help you get answers).