[R] converting "by" to a data.frame?
Thomas Lumley
tlumley at u.washington.edu
Fri Jun 6 00:23:59 CEST 2003
On Thu, 5 Jun 2003, Spencer Graves wrote:
> Dear R-Help:
>
> I want to (a) subset a data.frame by several columns, (b) fit a model
> to each subset, and (c) store a vector of results from the fit in the
> columns of a data.frame. In the past, I've used "for" loops do do this.
> Is there a way to use "by"?
>
> Consider the following example:
>
> > byFits <- by(by.df, list(A=by.df$A, B=by.df$B),
> + function(data.)coef(lm(y~x, data.)))
> > byFits
> A: A1
> B: B1
> (Intercept) x
> 3.333333e-01 -1.517960e-16
> ------------------------------------------------------------
> A: A2
> B: B1
> NULL
> ------------------------------------------------------------
> A: A1
> B: B2
> NULL
> ------------------------------------------------------------
> A: A2
> B: B2
> (Intercept) x
> 6.666667e-01 3.282015e-16
> >
> >
> #############################
> Desired output:
>
> data.frame(A=c("A1","A2"), B=c("B1", "B2"),
> .Intercept.=c(1/3, 2/3), x=c(-1.5e-16, 3.3e-16))
>
> What's the simplest way to do this?
do.call("rbind", byFits)
-thomas
More information about the R-help
mailing list