[R] coefficients lm of data.frame
    Hadley Wickham 
    hadley at rice.edu
       
    Fri Jul  8 00:35:37 CEST 2011
    
    
  
On Thu, Jul 7, 2011 at 5:24 PM, Dennis Murphy <djmuser at gmail.com> wrote:
> Hi:
>
> Here's another approach using the plyr package:
>
> library(plyr)
> df <- data.frame(gp = factor(rep(1:3, each = 4)), x = rnorm(12), y = rnorm(12))
> mylst <- split(df, df$gp)
> mycoefs <-  ldply(mylst, function(d) coef(lm(y ~ x, data = d)))
> names(mycoefs) <- c('gp', 'intercept', 'slope')
> merge(df, mycoefs, by = 'gp', all.x = TRUE)
>
> One could write this more compactly as
>
> dfr <- merge(df, ldply(split(df, df$gp), function(d) coef(lm(y ~ x, data = d))),
>                     by.x = 'gp', by.y = '.id', all.x = TRUE)
Or even more compactly as
dfr <- merge(df, ddply(df, "gp", function(d) coef(lm(y ~ x, data = d))),
                    by.x = 'gp', by.y = '.id', all.x = TRUE)
Hadley
-- 
Assistant Professor / Dobelman Family Junior Chair
Department of Statistics / Rice University
http://had.co.nz/
    
    
More information about the R-help
mailing list