Merge pull request #81 from CartoDB/equalint
adding equal interval function for consistency
This commit is contained in:
commit
b9fe204007
37
scripts-available/CDB_EqualIntervalBins.sql
Normal file
37
scripts-available/CDB_EqualIntervalBins.sql
Normal file
@ -0,0 +1,37 @@
|
||||
--
|
||||
-- Calculate the equal interval bins for a given column
|
||||
--
|
||||
-- @param in_array A numeric array of numbers to determine the best
|
||||
-- to determine the bin boundary
|
||||
--
|
||||
-- @param breaks The number of bins you want to find.
|
||||
--
|
||||
--
|
||||
-- Returns: upper edges of bins
|
||||
--
|
||||
--
|
||||
|
||||
CREATE OR REPLACE FUNCTION CDB_EqualIntervalBins ( in_array NUMERIC[], breaks INT ) RETURNS NUMERIC[] as $$
|
||||
DECLARE
|
||||
diff numeric;
|
||||
min_val numeric;
|
||||
max_val numeric;
|
||||
tmp_val numeric;
|
||||
i INT := 1;
|
||||
reply numeric[];
|
||||
BEGIN
|
||||
SELECT min(e), max(e) INTO min_val, max_val FROM ( SELECT unnest(in_array) e ) x WHERE e IS NOT NULL;
|
||||
diff = (max_val - min_val) / breaks::numeric;
|
||||
LOOP
|
||||
IF i < breaks THEN
|
||||
tmp_val = min_val + i::numeric * diff;
|
||||
reply = array_append(reply, tmp_val);
|
||||
i := i+1;
|
||||
ELSE
|
||||
reply = array_append(reply, max_val);
|
||||
EXIT;
|
||||
END IF;
|
||||
END LOOP;
|
||||
RETURN reply;
|
||||
END;
|
||||
$$ language plpgsql IMMUTABLE;
|
1
scripts-enabled/240-CDB_EqualIntervalBins.sql
Symbolic link
1
scripts-enabled/240-CDB_EqualIntervalBins.sql
Symbolic link
@ -0,0 +1 @@
|
||||
../scripts-available/CDB_EqualIntervalBins.sql
|
5
test/CDB_EqualIntervalBinsTest.sql
Normal file
5
test/CDB_EqualIntervalBinsTest.sql
Normal file
@ -0,0 +1,5 @@
|
||||
WITH data AS (
|
||||
SELECT array_agg(x::numeric) s FROM generate_series(1,300) x
|
||||
WHERE x % 5 != 0 AND x % 7 != 0
|
||||
)
|
||||
SELECT round(unnest(CDB_EqualIntervalBins(s, 7)),7) FROM data
|
7
test/CDB_EqualIntervalBinsTest_expect
Normal file
7
test/CDB_EqualIntervalBinsTest_expect
Normal file
@ -0,0 +1,7 @@
|
||||
43.5714286
|
||||
86.1428571
|
||||
128.7142857
|
||||
171.2857143
|
||||
213.8571429
|
||||
256.4285714
|
||||
299.0000000
|
Loading…
Reference in New Issue
Block a user