[R] for loop and linear models

Dennis Murphy djmuser at gmail.com
Mon Jun 20 23:52:11 CEST 2011


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.
>



More information about the R-help mailing list