roll_mean: Efficient rolling mean

Description Usage Arguments Details Value See Also Examples

Description

Generate a (right-aligned) rolling mean for a vector, optionally applying exponential weights.

Usage

1
roll_mean(x, window, na.rm = TRUE, ema = FALSE)

Arguments

x

numeric vector to be rolled over.

window

integer; the window size in vector element units. This argument is silently truncated.

na.rm

logical; should NAs be discarded?

ema

logical; return an "exponentially weighted moving average"?

Details

This function rolls over x by "element", i.e. window = 10 will average over 10 adjacent values in x. This is emphasised as often a time-windowed rolling average is desired. The latter can only be achieved if data are sampled uniformly, i.e. a window = 10 rolling mean will also give a 10-second moving average with data sampled at 1 Hz. If data are not sampled consistently, consider resampling with resample.

The rolling mean returned here is right-aligned, padded with leading zeros. That is, there are window - 1 zeros at the start of the return vector.

Note that the window argument is silently truncated (trunc). This because a floating-point window size makes no sense...

Value

A vector of the same length as x.

See Also

roll_mean.time for rolling over messily sampled data.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
library(dplyr, warn.conflicts = FALSE)
data(chaingang)

# The 'chaingang' dataset is sampled at 1 Hz
# without any breaks.
diff(chaingang$time.s) %>% unique  # NB!

# 30 second rolling mean, and 25 second exponentially-
# weighted rolling mean.
chaingang <- mutate(chaingang,
                    power.30mean = roll_mean(power.W, 30),
                    power.25ema = roll_mean(power.W, 25, ema = TRUE))

chaingang <- chaingang[-(1:29), ]  # Remove zero padding.

plot(power.W ~ time.s, type = "l", col = "gray", data = chaingang)
lines(power.25ema ~ time.s, data = chaingang)

# FYI:
normalised_power <- mean(chaingang$power.30mean^4) ^ (1/4)
xPower <- mean(chaingang$power.25ema^4) ^ (1/4)

jmackie4/elpatron documentation built on May 19, 2019, 12:49 p.m.