# [R] weighted average grouped by variables

Berend Hasselman bhh at xs4all.nl
Sat Nov 11 11:25:59 CET 2017

```> On 9 Nov 2017, at 14:58, PIKAL Petr <petr.pikal at precheza.cz> wrote:
>
> Hi
>
> Thanks for working example.
>
> you could use split/ lapply approach, however it is probably not much better than dplyr method.
>
> sapply(split(mydf, mydf\$type), function(speed, n_vehicles) sum(mydf\$speed*mydf\$n_vehicles)/sum(mydf\$n_vehicles))
> gives you averages
>

The result of this calculation is:

car light_duty heavy_duty motorcycle
36.54109   36.54109   36.54109   36.54109

But this doesn't give the same result as the dplyr method which is:

date_time       type      vel
<dttm>     <fctr>    <dbl>
1 2017-10-17 13:00:00        car 36.39029
2 2017-10-17 13:00:00 light_duty 38.56522
3 2017-10-17 13:00:00 heavy_duty 37.53333
4 2017-10-17 13:00:00 motorcycle 36.08696

The base R way of getting the result should be modified slightly into

sapply(split(mydf, mydf\$type), function(Z) sum(Z\$speed*Z\$n_vehicles)/sum(Z\$n_vehicles))

Calculations are done on the elements of the list provided by split.
The result now is:

car light_duty heavy_duty motorcycle
36.39029   38.56522   37.53333   36.08696

Obviously now the same as the dplyr method.

Berend Hasselman

> aggregate(mydf\$n_vehicles, list(mydf\$type), sum)\$x
> gives you sums
>
> Cheers
> Petr
>
>> -----Original Message-----
>> From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of Massimo
>> Bressan
>> Sent: Thursday, November 9, 2017 2:17 PM
>> To: r-help <r-help at r-project.org>
>> Subject: Re: [R] weighted average grouped by variables
>>
>> Hello
>>
>> an update about my question: I worked out the following solution (with the
>> package "dplyr")
>>
>> library(dplyr)
>>
>> mydf%>%
>> mutate(speed_vehicles=n_vehicles*mydf\$speed) %>%
>> group_by(date_time,type) %>%
>> summarise(
>> sum_n_times_speed=sum(speed_vehicles),
>> n_vehicles=sum(n_vehicles),
>> vel=sum(speed_vehicles)/sum(n_vehicles)
>> )
>>
>>
>> In fact I was hoping to manage everything in a "one-go": i.e. without the need
>> to create the "intermediate" variable called "speed_vehicles" and with the use
>> of the function weighted.mean()
>>
>> any hints for a different approach much appreciated
>>
>> thanks
>>
>>
>>
>> Da: "Massimo Bressan" <massimo.bressan at arpa.veneto.it>
>> A: "r-help" <r-help at r-project.org>
>> Inviato: Giovedì, 9 novembre 2017 12:20:52
>> Oggetto: weighted average grouped by variables
>>
>> hi all
>>
>> I have this dataframe (created as a reproducible example)
>>
>> mydf<-structure(list(date_time = structure(c(1508238000, 1508238000,
>> 1508238000, 1508238000, 1508238000, 1508238000, 1508238000), class =
>> c("POSIXct", "POSIXt"), tzone = ""), direction = structure(c(1L, 1L, 1L, 1L, 2L, 2L,
>> 2L), .Label = c("A", "B"), class = "factor"), type = structure(c(1L, 2L, 3L, 4L, 1L,
>> 2L, 3L), .Label = c("car", "light_duty", "heavy_duty", "motorcycle"), class =
>> "factor"), avg_speed = c(41.1029082774049, 40.3333333333333,
>> 40.3157894736842, 36.0869565217391, 33.4065155807365,
>> 37.6222222222222, 35.5), n_vehicles = c(447L, 24L, 19L, 23L, 706L, 45L, 26L)),
>> .Names = c("date_time", "direction", "type", "speed", "n_vehicles"), row.names
>> = c(NA, -7L), class = "data.frame")
>>
>> mydf
>>
>> and I need to get to this final result
>>
>> mydf_final<-structure(list(date_time = structure(c(1508238000, 1508238000,
>> 1508238000, 1508238000), class = c("POSIXct", "POSIXt"), tzone = ""), type =
>> structure(c(1L, 2L, 3L, 4L), .Label = c("car", "light_duty", "heavy_duty",
>> "motorcycle"), class = "factor"), weighted_avg_speed = c(36.39029, 38.56521,
>> 37.53333, 36.08696), n_vehicles = c(1153L,69L,45L,23L)), .Names =
>> c("date_time", "type", "weighted_avg_speed", "n_vehicles"), row.names =
>> c(NA, -4L), class = "data.frame")
>>
>> mydf_final
>>
>>
>> my question:
>> how to compute a weighted mean i.e. "weighted_avg_speed"
>> from "speed" (the values whose weighted mean is to be computed) and
>> "n_vehicles" (the weights) grouped by "date_time" and "type"?
>>
>> to be noted the complication of the case "motorcycle" (not present in both
>> directions)
>>
>> any help for that?
>>
>> thank you
>>
>> max
>>
>>
>>
>> --
>>
>> ------------------------------------------------------------
>> Massimo Bressan
>>
>> ARPAV
>> Agenzia Regionale per la Prevenzione e
>> Protezione Ambientale del Veneto
>>
>> Dipartimento Provinciale di Treviso
>> Via Santa Barbara, 5/a
>> 31100 Treviso, Italy
>>
>> tel: +39 0422 558545
>> fax: +39 0422 558516
>> e-mail: massimo.bressan at arpa.veneto.it
>> ------------------------------------------------------------
>>
>>
>>      [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> and provide commented, minimal, self-contained, reproducible code.
>
> ________________________________
> Tento e-mail a jakékoliv k němu připojené dokumenty jsou důvěrné a jsou určeny pouze jeho adresátům.
> Jestliže jste obdržel(a) tento e-mail omylem, informujte laskavě neprodleně jeho odesílatele. Obsah tohoto emailu i s přílohami a jeho kopie vymažte ze svého systému.
> Nejste-li zamýšleným adresátem tohoto emailu, nejste oprávněni tento email jakkoliv užívat, rozšiřovat, kopírovat či zveřejňovat.
> Odesílatel e-mailu neodpovídá za eventuální škodu způsobenou modifikacemi či zpožděním přenosu e-mailu.
>
> V případě, že je tento e-mail součástí obchodního jednání:
> - vyhrazuje si odesílatel právo ukončit kdykoliv jednání o uzavření smlouvy, a to z jakéhokoliv důvodu i bez uvedení důvodu.
> - a obsahuje-li nabídku, je adresát oprávněn nabídku bezodkladně přijmout; Odesílatel tohoto e-mailu (nabídky) vylučuje přijetí nabídky ze strany příjemce s dodatkem či odchylkou.
> - trvá odesílatel na tom, že příslušná smlouva je uzavřena teprve výslovným dosažením shody na všech jejích náležitostech.
> - odesílatel tohoto emailu informuje, že není oprávněn uzavírat za společnost žádné smlouvy s výjimkou případů, kdy k tomu byl písemně zmocněn nebo písemně pověřen a takové pověření nebo plná moc byly adresátovi tohoto emailu případně osobě, kterou adresát zastupuje, předloženy nebo jejich existence je adresátovi či osobě jím zastoupené známá.
>
> This e-mail and any documents attached to it may be confidential and are intended only for its intended recipients.
> If you received this e-mail by mistake, please immediately inform its sender. Delete the contents of this e-mail with all attachments and its copies from your system.
> If you are not the intended recipient of this e-mail, you are not authorized to use, disseminate, copy or disclose this e-mail in any manner.
> The sender of this e-mail shall not be liable for any possible damage caused by modifications of the e-mail or by delay with transfer of the email.
>
> In case that this e-mail forms part of business dealings:
> - the sender reserves the right to end negotiations about entering into a contract in any time, for any reason, and without stating any reasoning.
> - if the e-mail contains an offer, the recipient is entitled to immediately accept such offer; The sender of this e-mail (offer) excludes any acceptance of the offer on the part of the recipient containing any amendment or variation.
> - the sender insists on that the respective contract is concluded only upon an express mutual agreement on all its aspects.
> - the sender of this e-mail informs that he/she is not authorized to enter into any contracts on behalf of the company except for cases in which he/she is expressly authorized to do so in writing, and such authorization or power of attorney is submitted to the recipient or the person represented by the recipient, or the existence of such authorization is known to the recipient of the person represented by the recipient.
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help