Sliding Window calculations in #Clojure

For time series calculations the sliding window is a tool for applying some calculation against the numbers in incremental stages.

This could be calculation the average temperature across a series or readings, or heart rate or something similar.

A set of numbers…. here you are in your REPL.

user> (def readings [1 3 4 5 3 4 2 6 5 4 3 5 7 8])
#'user/readings

The partition function will split those numbers up into a sequence of sequences. This is effectively your set of sliding windows.

user> (partition 3 1 readings)
((1 3 4) (3 4 5) (4 5 3) (5 3 4) (3 4 2) (4 2 6) (2 6 5) (6 5 4) (5 4 3) (4 3 5) (3 5 7) (5 7 8))

You can see the partition function has created a set for the first three numbers, then stepped one number to the right and created another set. It does that for the entire sequence of numbers you supply it.

Perhaps you want to calculate the average of each set of numbers. You can now apply a map function to work on each set the partition function has given you.

user> (map (fn [window] (double (/ (apply + window) (count window)))) (partition 3 1 readings))

(2.666666666666667 4.0 4.0 4.0 3.0 4.0 4.333333333333333 5.0 4.0 4.0 5.0 6.666666666666667)

Handy for monitoring internet of things readings and getting the average. Actually loads of uses when start thinking of the possibilities.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: