File: window.mlr

package info (click to toggle)
miller 6.16.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 87,928 kB
  • sloc: ruby: 162; sh: 119; makefile: 87
file content (56 lines) | stat: -rw-r--r-- 1,482 bytes parent folder | download | duplicates (3)
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# ================================================================
# Sliding average with window over n previous rows and current row.
# ================================================================

begin {
  # INPUT PARAMETERS
  # They can do 'mlr put -s window_size=4 -s input_field_names=x,y ...'
  if (is_absent(@window_size)) {
    @window_size = 3;
  }
  # In Miller 6 (Go port) we'll have arrays and you'll be able to do
  # @input_field_names = ["x", "y"].
  if (is_absent(@input_field_names)) {
    @input_field_names = splitax("x,y", ",")
  } else {
    @input_field_names = splitax(@input_field_names, ",")
  }

  # INITIALIZATION
  @output_field_names = {};
  for (name in @input_field_names) {
    @output_field_names[name] = name . "_avg";
  }
  for (name in @input_field_names) {
    for (i = 0; i < @window_size; i+=1) {
      @windows[name][i] = 0;
    }
  }
  # dump;
}

# Slide the windows
for (name in @input_field_names) {
  for (i = 1; i < @window_size; i+=1) {
    @windows[name][i-1] = @windows[name][i];
  }
}
# Update the windows with new data
for (name in @input_field_names) {
  @windows[name][@window_size - 1] = $[name];
}

# Compute the averages
sums = {};
for (name in @input_field_names) {
  for (i = 0; i < @window_size; i+=1) {
    sums[name] += @windows[name][i];
  }
}
denominator = @window_size;
if (NR < @window_size) {
    denominator = NR
}
for (name in @input_field_names) {
  $[@output_field_names[name]] = sums[name] / denominator;
}