Calculate interquartile mean from Ruby array?

I have this array:

[288.563044, 329.835918, 578.622569, 712.359026, 866.614253, 890.066321, 1049.78037, 1070.29897, 2185.443662, 2492.245562, 4398.300227, 13953.264379] 

How can I calculate the interquartile average of this?

This Wikipedia link explains this best, but I basically need to remove the lower and upper 25%, leaving only the average 50%, of which I will need to average the numbers.

But provided that the number of elements in the array is divided by 4. Here, how to calculate it when it is not divided by four.

So how would I do that?

+4
source share
3 answers

This is a partial solution for an array with the number of elements, which is a multiple of 4. I will put the full text when I find out.

 arr = [288.563044, 329.835918, 578.622569, 712.359026, 866.614253, 890.066321, 1049.78037, 1070.29897, 2185.443662, 2492.245562, 4398.300227, 13953.264379].sort! length = arr.size mean = arr.sort[(length/4)..-(length/4+1)].inject(:+)/(length/2) 

I think this is the best solution.

 def interquartile_mean(array) arr = array.sort length = arr.size quart = (length/4.0).floor fraction = 1-((length/4.0)-quart) new_arr = arr[quart..-(quart + 1)] (fraction*(new_arr[0]+new_arr[-1]) + new_arr[1..-2].inject(:+))/(length/2.0) end 
+4
source

A simple case of array_size mod 4 = 0 :

 xs = [5, 8, 4, 38, 8, 6, 9, 7, 7, 3, 1, 6] q = xs.size / 4 ys = xs.sort[q...3*q] mean = ys.inject(0, :+) / ys.size.to_f #=> 6.5 

General case ( array_size >= 4 ):

 xs = [1, 3, 5, 7, 9, 11, 13, 15, 17] q = xs.size / 4.0 ys = xs.sort[q.ceil-1..(3*q).floor] factor = q - (ys.size/2.0 - 1) mean = (ys[1...-1].inject(0, :+) + (ys[0] + ys[-1]) * factor) / (2*q) #=> 9.0 

However, if you are not trying to encode it yourself, this will not help ...

+2
source

Improving tokland's answer to what increases the Array class and fixes the edge of the edge (the method, as written, blows with an array size of 4).

 class Array def interquartile_mean a = sort l = size quart = (l.to_f / 4).floor t = a[quart..-(quart + 1)] t.inject{ |s, e| s + e }.to_f / t.size end end 
+1
source

Source: https://habr.com/ru/post/1390909/


All Articles