[R] tapply for function taking of >1 argument?

Gabor Grothendieck ggrothendieck at gmail.com
Wed Feb 3 19:16:48 CET 2010


Also try this:

> library(sqldf)
> DF <- data.frame(data = 1:10, groups = rep(1:2, 5), weights = 1)
> sqldf("select groups, sum(data * weights)/sum(weights) 'wtd mean' from DF group by groups")
  groups wtd mean
1      1        5
2      2        6

On Tue, Feb 2, 2010 at 5:06 PM, sjaffe <sjaffe at riskspan.com> wrote:
>
> Thanks! :-)
>
> I suppose it's obvious, but one will generally have to use a (anonymous)
> function to 'unpack' the data.frame into columns, unless the function
> already knows how to do this.
>
> I mention this because when I tested the solution on my example I got an
> unexpected result -- apparently weighted.mean will operate on a 2-column
> dataframe but not in the way one would expect.
>
> data = 1:10
> weights = rep(1,10)
> groups = rep(c(1,2),5)
>  by( data.frame(data,weights), groups, weighted.mean)
> groups: 1
> [1] 15
> ------------------------------------------------------------
> groups: 2
> [1] 17.5
>>
>
>
> But
>
>  by( data.frame(data,weights), groups, function(d) { weighted.mean(d[,1],
> d[,2]) } )
>
> does the right thing
>
> groups: 1
> [1] 5
> ------------------------------------------------------------
> groups: 2
> [1] 6
>>
>
>
>
> Bert Gunter wrote:
>>
>> ?by
>>
>
>> Bert Gunter
>> Genentech Nonclinical Statistics
>>
> --
> View this message in context: http://n4.nabble.com/tapply-for-function-taking-of-1-argument-tp1460392p1460489.html
> Sent from the R help mailing list archive at Nabble.com.
>
>        [[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