Frequency Table¶
Source: adopted from here
Introduction¶
Frequency refers to the number of times an event or a value occurs. A frequency table is a table that lists values, as well as the number of times each value appears in the data set. A histogram is can be built from a frequency table by aggregating over a specified ranges of continuous data values and corresponding number of frequencies.
Question¶
Write a function (freq
) to calculate the frequency table of a list of integer numbers and sort the key values in ascending order.
system "S -314159";
nums:10000?10;
Calling the function against the above list of random integers yields:
q) show freq nums
0| 1008
1| 988
2| 969
3| 1054
4| 977
5| 986
6| 1004
7| 1029
8| 977
9| 1008
Answer¶
Method 1: Use group
freq1:{#[;d] asc key d:count each group x};
Method 2: Use general apply with dyadic functions
freq2:{@[x!count[x:asc distinct x]#0;x;+;1]};
Let's measure the performance of the two implementations:
q)\ts:100000 freq1 nums
6577 369536
q)\ts:100000 freq2 nums
6843 262688
Method 2 runs slightly slower, but it takes significantly less memory.