typestar

Moving average in R

A rolling mean with filter, and the NA padding at the edges.

moving_average <- function(x, window) {
  n <- length(x) - window + 1
  sapply(seq_len(n), function(i) {
    mean(x[i:(i + window - 1)])
  })
}

Keywords and builtins used here

The run, in numbers

Lines
6
Characters to type
133
Tokens
49
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 33 seconds.

Type this snippet

Step 5 of 5 in Vectorized thinking, step 14 of 20 in Language basics.

← Previous Next →

Moving average in other languages