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]]
An embedded message was scrubbed... From: "Filipe Leme Botelho" <filipe.botelho at vpar.com.br> Subject: RES: [R] for loop and linear models Date: Mon, 20 Jun 2011 16:41:46 -0300 Size: 2804 URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20110620/718bd446/attachment.mht> -------------- next part -------------- "This message and its attachments may contain confidential and/or privileged information. If you are not the addressee, please, advise the sender immediately by replying to the e-mail and delete this message." "Este mensaje y sus anexos pueden contener informaci?n confidencial o privilegiada. Si ha recibido este e-mail por error por favor b?rrelo y env?e un mensaje al remitente." "Esta mensagem e seus anexos podem conter informa??o confidencial ou privilegiada. Caso n?o seja o destinat?rio, solicitamos a imediata notifica??o ao remetente e exclus?o da mensagem."
Hi, can you put "return(models)" within the inner braces and report what it does. That might do the trick, since it should return the 'models' for every combination of i and j. HTH, 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-tp3612274p3612388.html Sent from the R help mailing list archive at Nabble.com.
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.
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-tp3612274p3612392.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. >
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
Hi: (a) What Brian said... (b) Here's one way to generate a list of model objects from which you can extract the pieces you may want. # Generate a fairly minimal, reproducible data set set.seed(345) # makes results below reproducible dd <- data.frame(X = rnorm(100), Y = rnorm(100), gp = factor(rep(LETTERS[1:5], each = 20))) # Basically, split the data frame by gp into a list of sub-data frames # and fit lm() to each piece. We use the plyr package for this: library(plyr) mlist <- dlply(dd, .(gp), function(d) lm(Y ~ X, data = d)) # mlist is a list of lm objects, from which you can extract salient # pieces using the l*ply functions from plyr. For example, # return the coefficients from each model fit:> ldply(mlist, coef)gp (Intercept) X 1 A -0.05670893 -0.008741077 2 B -0.41071309 -0.134832968 3 C -0.02007992 0.379762195 4 D 0.04168990 0.213085495 5 E 0.19094314 0.010481033 # R^2:> ldply(mlist, function(m) summary(m)$r.squared)gp V1 1 A 9.287934e-05 2 B 1.684219e-02 3 C 1.200286e-01 4 D 4.235989e-02 5 E 7.294735e-05 # Table of coefficients, SEs and significance tests # (outputs a list) llply(mlist, function(m) summary(m)$coefficients) # Data frame of predicted values and residuals (multiple outputs): ldply(mlist, function(m) data.frame(pred = fitted(m), res = resid(m))) HTH, Dennis On Mon, Jun 20, 2011 at 12:23 PM, ivan <i.petzev at gmail.com> 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. >