I'm sure I can put this together from the various 'apply's and split, but I wonder if anyone has a quick incantation: E.g. I can do tapply( data, groups, mean) but how can I do something like: tapply( list(data,weights), groups, weighted.mean ) ? (or: mapply is to sapply as ? is to tapply ) Thanks for your help. -- View this message in context: http://n4.nabble.com/tapply-for-function-taking-of-1-argument-tp1460392p1460392.html Sent from the R help mailing list archive at Nabble.com.
Hi sjaffem, You were almost there: tapply( yourdata, groups, weighted.mean, weights) See ?tapply for more information. HTH, Jorge On Tue, Feb 2, 2010 at 3:58 PM, sjaffe <> wrote:> > I'm sure I can put this together from the various 'apply's and split, but I > wonder if anyone has a quick incantation: > > E.g. I can do tapply( data, groups, mean) > > but how can I do something like: tapply( list(data,weights), groups, > weighted.mean ) ? > > (or: mapply is to sapply as ? is to tapply ) > > Thanks for your help. > -- > View this message in context: > http://n4.nabble.com/tapply-for-function-taking-of-1-argument-tp1460392p1460392.html > Sent from the R help mailing list archive at Nabble.com. > > ______________________________________________ > 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. >[[alternative HTML version deleted]]
On Wed, Feb 3, 2010 at 11:06 AM, David Freedman <3.14david at gmail.com> wrote:> > also, > > library(plyr) > ddply(d,~grp,function(df) weighted.mean(df$x,df$w))Or ddply(d, "grp", summarise, mean = weighted.mean(x, w)) which is convenient if you want more than one output Hadley -- http://had.co.nz/
sjaffe wrote:> I'm sure I can put this together from the various 'apply's and split, but I > wonder if anyone has a quick incantation: > > E.g. I can do tapply( data, groups, mean) > > but how can I do something like: tapply( list(data,weights), groups, > weighted.mean ) ? > > (or: mapply is to sapply as ? is to tapply ) > > Thanks for your help.coef(lm(data ~ -1 + as.factor(groups), weights=weights)) Not the fastest, but IMO more comprehensible than the constructions involving anonymous functions. J. R. M. Hosking