Displaying 6 results from an estimated 6 matches for "light_duti".
Did you mean:
light_duty
2017 Nov 09
4
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 =
2017 Nov 11
0
weighted average grouped by variables
> 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
2017 Nov 09
1
weighted average grouped by variables
Hello,
Using base R only, the following seems to do what you want.
with(mydf, ave(speed, date_time, type, FUN = weighted.mean, w = n_vehicles))
Hope this helps,
Rui Barradas
Em 09-11-2017 13:16, Massimo Bressan escreveu:
> Hello
>
> an update about my question: I worked out the following solution (with the package "dplyr")
>
> library(dplyr)
>
> mydf%>%
>
2017 Nov 09
2
weighted average grouped by variables
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
aggregate(mydf$n_vehicles, list(mydf$type), sum)$x
gives you sums
Cheers
Petr
> -----Original Message-----
> From: R-help
2017 Nov 09
0
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
2017 Nov 09
1
weighted average grouped by variables
Dear Massimo,
It seems straightforward to use weighted.mean() in a dplyr context
library(dplyr)
mydf %>%
group_by(date_time, type) %>%
summarise(vel = weighted.mean(speed, n_vehicles))
Best regards,
ir. Thierry Onkelinx
Statisticus / Statistician
Vlaamse Overheid / Government of Flanders
INSTITUUT VOOR NATUUR- EN BOSONDERZOEK / RESEARCH INSTITUTE FOR NATURE AND
FOREST
Team