Calculate Median/Modus/Average Subflow
Introduction
This subflow is part of our Internal flows collection. Internal flows are used for manipulating and storing data inside Node-RED.
Prerequisites
This flow along with other data generating nodes and flows is available for user in the following package:
@senlab/node-red-statistics-senlab
To learn more about Verdaccio and how to install packages, please refer to this documentation: Verdaccio
Setting I/O nodes and environmental variables
When creating a subflow user needs to define input node and one or more output nodes, so the messages can pass through our custom implementation. In the top bar there are configuration options enabling us to do that.
image::subflows-config.png
Environmental variables can be added to the subflow using the edit properties window, where user can also change the name of the subflow. Environmental variables can be used to make subflow configurable (make subflow reusable in different configurations). For example user can specify environmental variable named addID which is of type boolean and build custom implementation of the code based on this environmental variable where subflow outputs JS object which does or doesnt include ID based on selected option when deploying the subflow.
Inside the subflow environmental variables are accessible with: env.get(’);
This subflow uses 1 environmental variable named statChoice, working of the subflow strongly depends on this variable. Based on this variable operation is choosed between median, modus and average.
Prerequisites
This subflow calculates statistical operation based on incomming array, which can be constructed using saveData subflow, which using context saves array and passes it on in msg object. To read more about saveData subflow visit this link: …
Setting Function Node for statistical operations
Function Node is powerful Node-RED node which enables us to add our Custom Javascript code to Node-RED without the need to make custom nodes.
Environmental variable is used to determine which operation the subflow should execute, user can choose between median, modus and average. Environmental variable can be accessed inside the function node like this:
let statChoice = env.get('statChoice');
This subflow only calculates statistical operations on the last 1000 elements from the passed array:
if (savedArray.length > 1000) {
var inputArray = savedArray.slice(-1000);
} else {
var inputArray = savedArray;
}
3 functions are defined based on selected operation named findModus, findMedian and findAverage, switch-case statement is used to call correct function.
You can see logic for functions if you open function node inside this subflow.
Calculated stat is outputed outside the subflow inside payload property.