On Thu, Jul 7, 2011 at 5:24 PM, Dennis Murphy <djmu...@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/

______________________________________________
R-help@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.

Reply via email to