r/rstats•
textrant

How to do a grouped weighted Median?

Hi, i'm new to using R and I'm trying to find a grouped weighted median. It is simple to get the grouped weighted mean, but i can't seem to find a workable function using google to do this.

The data looks something like the following

EventIDVolume
11.150
11.210
11.310
11.410
11.510
21.110
21.210
21.330
21.720
21.930
31.420
31.510
31.610
31.710
31.85

and the result i'd want returned is

EventMedianID
11.1
21.5
31.5

Can anyone help with this?

Posted Sep 4, 2016, 9:15 AM UTC

310
rp2ne1•

I imported your data in a data.table (Data). This line of code would give you the result:

library(data.table)

Data <- fread("Data.csv")

Data[,median(rep( ID, times= Volume)), by = Event]

Event V1

1 1.1

2 1.5

3 1.5

6
hadley•

That is a very inefficient implementation

3
onRedditWithBeer•

What makes this inefficient?

2
__nev__•

It doesn't scale well with arbitrarily large Volume and group size. You risk memory overflow.

5
onRedditWithBeer•

Gotcha, thanks. What would a better implementation look like?

1