This post shows how to find the Interquartile Range (IQR) in Julia. We will use custom codes and move them into a function for reusability.
Interquartile Range With Custom Codes
Before moving on, please install Julia plugin for IntelliJ IDEA. Using IntelliJ IDEA may be optional for those who already have other IDEs. In this section, we’ll create simple Julia codes to find the Interquartile Range of a given array of integers.
First, we bring in the Statistics package to compute for the median values later.
1 | using Statistics |
We have these sample values stored in an array.
1 | samples = [98, 90, 70, 18, 92, 92, 55, 83, 45, 95, 88, 76] |
Then, we sort the values.
1 | samples = sort(samples) |
We find the length of the array to split it into two using the built-in Julia function length.
1 2 3 4 5 | # Get the size of the samples samples_len = length(samples) # Divide the size by 2 sub_samples_len = div(samples_len, 2) |
Next, we find the start and end indexes for Q1 and Q3.
1 2 3 4 5 | start_index_of_q1 = 1 end_index_of_q1 = sub_samples_len start_index_of_q3 = samples_len - sub_samples_len + 1 end_index_of_q3 = samples_len |
Then, we find the median values from each half of the array. This function requires the Julia Statistics package.
1 2 3 4 5 | # Q1 median value median_value_of_q1 = median(view(samples, start_index_of_q1:end_index_of_q1)) # Q2 median value median_value_of_q3 = median(view(samples, start_index_of_q3:end_index_of_q3)) |
Lastly, we get the difference between the two median values, which is our Interquartile Result.
1 | iqr_result = median_value_of_q3 - median_value_of_q1 |
Find Interquartile Range With a Function
Okay, from the code fragments we have, we can create our function in Julia to find the Interquartile Range. We will name our function my_iqr. Its definition is shown as follows.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | function my_iqr(samples) samples = sort(samples) # Get the size of the samples samples_len = length(samples) # Divide the size by 2 sub_samples_len = div(samples_len, 2) # Know the indexes start_index_of_q1 = 1 end_index_of_q1 = sub_samples_len start_index_of_q3 = samples_len - sub_samples_len + 1 end_index_of_q3 = samples_len # Q1 median value median_value_of_q1 = median(view(samples, start_index_of_q1:end_index_of_q1)) # Q2 median value median_value_of_q3 = median(view(samples, start_index_of_q3:end_index_of_q3)) # Find the IQR value iqr_result = median_value_of_q3 - median_value_of_q1 return iqr_result end |
We still need to use the Statistics package, though. Also, the function definition goes first before in the file before any codes use it.
1 2 3 4 5 6 7 8 | # ... # Using Statistics # ... # my_iqr function definition here # samples = [98, 90, 70, 18, 92, 92, 55, 83, 45, 95, 88, 76] print(my_iqr(samples)) |
The codes produce a value of 29.5 for those integer values.